github.com/igoogolx/clash@v1.19.8/constant/dns.go (about)

     1  package constant
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  )
     8  
     9  // DNSModeMapping is a mapping for EnhancedMode enum
    10  var DNSModeMapping = map[string]DNSMode{
    11  	DNSNormal.String(): DNSNormal,
    12  	DNSFakeIP.String(): DNSFakeIP,
    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(any) 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 fmt.Errorf("invalid mode: %s", tp)
    32  	}
    33  	*e = mode
    34  	return nil
    35  }
    36  
    37  // MarshalYAML serialize EnhancedMode with yaml
    38  func (e DNSMode) MarshalYAML() (any, 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  }