github.com/yaling888/clash@v1.53.0/tunnel/mode.go (about)

     1  package tunnel
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"strings"
     7  )
     8  
     9  type TunnelMode int
    10  
    11  // ModeMapping is a mapping for Mode enum
    12  var ModeMapping = map[string]TunnelMode{
    13  	Global.String(): Global,
    14  	Rule.String():   Rule,
    15  	Script.String(): Script,
    16  	Direct.String(): Direct,
    17  }
    18  
    19  const (
    20  	Global TunnelMode = iota
    21  	Rule
    22  	Script
    23  	Direct
    24  )
    25  
    26  // UnmarshalJSON unserialize Mode
    27  func (m *TunnelMode) UnmarshalJSON(data []byte) error {
    28  	var tp string
    29  	json.Unmarshal(data, &tp)
    30  	mode, exist := ModeMapping[strings.ToLower(tp)]
    31  	if !exist {
    32  		return errors.New("invalid mode")
    33  	}
    34  	*m = mode
    35  	return nil
    36  }
    37  
    38  // UnmarshalYAML unserialize Mode with yaml
    39  func (m *TunnelMode) UnmarshalYAML(unmarshal func(any) error) error {
    40  	var tp string
    41  	unmarshal(&tp)
    42  	mode, exist := ModeMapping[strings.ToLower(tp)]
    43  	if !exist {
    44  		return errors.New("invalid mode")
    45  	}
    46  	*m = mode
    47  	return nil
    48  }
    49  
    50  // MarshalJSON serialize Mode
    51  func (m TunnelMode) MarshalJSON() ([]byte, error) {
    52  	return json.Marshal(m.String())
    53  }
    54  
    55  // MarshalYAML serialize TunnelMode with yaml
    56  func (m TunnelMode) MarshalYAML() (any, error) {
    57  	return m.String(), nil
    58  }
    59  
    60  func (m TunnelMode) String() string {
    61  	switch m {
    62  	case Global:
    63  		return "global"
    64  	case Rule:
    65  		return "rule"
    66  	case Script:
    67  		return "script"
    68  	case Direct:
    69  		return "direct"
    70  	default:
    71  		return "Unknown"
    72  	}
    73  }