clash/tunnel/mode.go

70 lines
1.2 KiB
Go
Raw Permalink Normal View History

2018-11-21 05:47:46 +00:00
package tunnel
import (
"encoding/json"
"errors"
"strings"
2018-11-21 05:47:46 +00:00
)
type TunnelMode int
2018-11-21 05:47:46 +00:00
2021-10-10 15:44:09 +00:00
// ModeMapping is a mapping for Mode enum
var ModeMapping = map[string]TunnelMode{
Global.String(): Global,
Rule.String(): Rule,
Direct.String(): Direct,
}
2018-11-21 05:47:46 +00:00
const (
Global TunnelMode = iota
2018-11-21 05:47:46 +00:00
Rule
Direct
)
// UnmarshalJSON unserialize Mode
func (m *TunnelMode) UnmarshalJSON(data []byte) error {
2018-11-21 05:47:46 +00:00
var tp string
2018-11-28 02:38:30 +00:00
json.Unmarshal(data, &tp)
mode, exist := ModeMapping[strings.ToLower(tp)]
2018-11-21 05:47:46 +00:00
if !exist {
return errors.New("invalid mode")
}
*m = mode
return nil
}
2018-12-05 13:13:29 +00:00
// UnmarshalYAML unserialize Mode with yaml
2022-03-16 04:10:13 +00:00
func (m *TunnelMode) UnmarshalYAML(unmarshal func(any) error) error {
2018-12-05 13:13:29 +00:00
var tp string
unmarshal(&tp)
mode, exist := ModeMapping[strings.ToLower(tp)]
2018-12-05 13:13:29 +00:00
if !exist {
return errors.New("invalid mode")
}
*m = mode
return nil
}
2018-11-21 05:47:46 +00:00
// MarshalJSON serialize Mode
func (m TunnelMode) MarshalJSON() ([]byte, error) {
2018-11-21 05:47:46 +00:00
return json.Marshal(m.String())
}
// MarshalYAML serialize TunnelMode with yaml
2022-03-16 04:10:13 +00:00
func (m TunnelMode) MarshalYAML() (any, error) {
return m.String(), nil
}
func (m TunnelMode) String() string {
2018-11-21 05:47:46 +00:00
switch m {
case Global:
return "global"
2018-11-21 05:47:46 +00:00
case Rule:
return "rule"
2018-11-21 05:47:46 +00:00
case Direct:
return "direct"
2018-11-21 05:47:46 +00:00
default:
2019-07-29 02:12:10 +00:00
return "Unknown"
2018-11-21 05:47:46 +00:00
}
}