github.com/chwjbn/xclash@v0.2.0/constant/dns.go (about)

     1  package constant
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  )
     7  
     8  // DNSModeMapping is a mapping for EnhancedMode enum
     9  var DNSModeMapping = map[string]DNSMode{
    10  	DNSNormal.String():  DNSNormal,
    11  	DNSFakeIP.String():  DNSFakeIP,
    12  	DNSMapping.String(): DNSMapping,
    13  }
    14  
    15  const (
    16  	DNSNormal DNSMode = iota
    17  	DNSFakeIP
    18  	DNSMapping
    19  )
    20  
    21  type DNSMode int
    22  
    23  // UnmarshalYAML unserialize EnhancedMode with yaml
    24  func (e *DNSMode) UnmarshalYAML(unmarshal func(interface{}) error) error {
    25  	var tp string
    26  	if err := unmarshal(&tp); err != nil {
    27  		return err
    28  	}
    29  	mode, exist := DNSModeMapping[tp]
    30  	if !exist {
    31  		return errors.New("invalid mode")
    32  	}
    33  	*e = mode
    34  	return nil
    35  }
    36  
    37  // MarshalYAML serialize EnhancedMode with yaml
    38  func (e DNSMode) MarshalYAML() (interface{}, error) {
    39  	return e.String(), nil
    40  }
    41  
    42  // UnmarshalJSON unserialize EnhancedMode with json
    43  func (e *DNSMode) UnmarshalJSON(data []byte) error {
    44  	var tp string
    45  	json.Unmarshal(data, &tp)
    46  	mode, exist := DNSModeMapping[tp]
    47  	if !exist {
    48  		return errors.New("invalid mode")
    49  	}
    50  	*e = mode
    51  	return nil
    52  }
    53  
    54  // MarshalJSON serialize EnhancedMode with json
    55  func (e DNSMode) MarshalJSON() ([]byte, error) {
    56  	return json.Marshal(e.String())
    57  }
    58  
    59  func (e DNSMode) String() string {
    60  	switch e {
    61  	case DNSNormal:
    62  		return "normal"
    63  	case DNSFakeIP:
    64  		return "fake-ip"
    65  	case DNSMapping:
    66  		return "redir-host"
    67  	default:
    68  		return "unknown"
    69  	}
    70  }