2022-03-09 05:08:35 +08:00
|
|
|
package constant
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
var StackTypeMapping = map[string]TUNStack{
|
2022-10-10 19:02:57 +08:00
|
|
|
strings.ToLower(TunGvisor.String()): TunGvisor,
|
|
|
|
strings.ToLower(TunSystem.String()): TunSystem,
|
2023-08-01 13:54:22 +08:00
|
|
|
strings.ToLower(TunMixed.String()): TunMixed,
|
2022-03-09 05:08:35 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
TunGvisor TUNStack = iota
|
|
|
|
TunSystem
|
2023-08-01 13:54:22 +08:00
|
|
|
TunMixed
|
2022-03-09 05:08:35 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type TUNStack int
|
|
|
|
|
|
|
|
// UnmarshalYAML unserialize TUNStack with yaml
|
2022-03-16 22:00:20 +08:00
|
|
|
func (e *TUNStack) UnmarshalYAML(unmarshal func(any) error) error {
|
2022-03-09 05:08:35 +08:00
|
|
|
var tp string
|
|
|
|
if err := unmarshal(&tp); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-10-10 19:02:57 +08:00
|
|
|
mode, exist := StackTypeMapping[strings.ToLower(tp)]
|
2022-03-09 05:08:35 +08:00
|
|
|
if !exist {
|
|
|
|
return errors.New("invalid tun stack")
|
|
|
|
}
|
|
|
|
*e = mode
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// MarshalYAML serialize TUNStack with yaml
|
2022-03-16 22:00:20 +08:00
|
|
|
func (e TUNStack) MarshalYAML() (any, error) {
|
2022-03-09 05:08:35 +08:00
|
|
|
return e.String(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// UnmarshalJSON unserialize TUNStack with json
|
|
|
|
func (e *TUNStack) UnmarshalJSON(data []byte) error {
|
|
|
|
var tp string
|
|
|
|
json.Unmarshal(data, &tp)
|
2022-10-10 19:02:57 +08:00
|
|
|
mode, exist := StackTypeMapping[strings.ToLower(tp)]
|
2022-03-09 05:08:35 +08:00
|
|
|
if !exist {
|
|
|
|
return errors.New("invalid tun stack")
|
|
|
|
}
|
|
|
|
*e = mode
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// MarshalJSON serialize TUNStack with json
|
|
|
|
func (e TUNStack) MarshalJSON() ([]byte, error) {
|
|
|
|
return json.Marshal(e.String())
|
|
|
|
}
|
|
|
|
|
2024-09-19 18:06:36 +08:00
|
|
|
// UnmarshalText unserialize TUNStack
|
|
|
|
func (e *TUNStack) UnmarshalText(data []byte) error {
|
|
|
|
mode, exist := StackTypeMapping[strings.ToLower(string(data))]
|
|
|
|
if !exist {
|
|
|
|
return errors.New("invalid tun stack")
|
|
|
|
}
|
|
|
|
*e = mode
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// MarshalText serialize TUNStack with json
|
|
|
|
func (e TUNStack) MarshalText() ([]byte, error) {
|
|
|
|
return []byte(e.String()), nil
|
|
|
|
}
|
|
|
|
|
2022-03-09 05:08:35 +08:00
|
|
|
func (e TUNStack) String() string {
|
|
|
|
switch e {
|
|
|
|
case TunGvisor:
|
|
|
|
return "gVisor"
|
|
|
|
case TunSystem:
|
|
|
|
return "System"
|
2023-08-01 13:54:22 +08:00
|
|
|
case TunMixed:
|
|
|
|
return "Mixed"
|
2022-03-09 05:08:35 +08:00
|
|
|
default:
|
|
|
|
return "unknown"
|
|
|
|
}
|
|
|
|
}
|