github.com/kelleygo/clashcore@v1.0.2/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 Direct.String(): Direct, 16 } 17 18 const ( 19 Global TunnelMode = iota 20 Rule 21 Direct 22 ) 23 24 // UnmarshalJSON unserialize Mode 25 func (m *TunnelMode) UnmarshalJSON(data []byte) error { 26 var tp string 27 json.Unmarshal(data, &tp) 28 mode, exist := ModeMapping[strings.ToLower(tp)] 29 if !exist { 30 return errors.New("invalid mode") 31 } 32 *m = mode 33 return nil 34 } 35 36 // UnmarshalYAML unserialize Mode with yaml 37 func (m *TunnelMode) UnmarshalYAML(unmarshal func(any) error) error { 38 var tp string 39 unmarshal(&tp) 40 mode, exist := ModeMapping[strings.ToLower(tp)] 41 if !exist { 42 return errors.New("invalid mode") 43 } 44 *m = mode 45 return nil 46 } 47 48 // MarshalJSON serialize Mode 49 func (m TunnelMode) MarshalJSON() ([]byte, error) { 50 return json.Marshal(m.String()) 51 } 52 53 // MarshalYAML serialize TunnelMode with yaml 54 func (m TunnelMode) MarshalYAML() (any, error) { 55 return m.String(), nil 56 } 57 58 func (m TunnelMode) String() string { 59 switch m { 60 case Global: 61 return "global" 62 case Rule: 63 return "rule" 64 case Direct: 65 return "direct" 66 default: 67 return "Unknown" 68 } 69 }