github.com/metacubex/mihomo@v1.18.5/tunnel/status.go (about) 1 package tunnel 2 3 import ( 4 "encoding/json" 5 "errors" 6 "strings" 7 "sync/atomic" 8 ) 9 10 type TunnelStatus int 11 12 // StatusMapping is a mapping for Status enum 13 var StatusMapping = map[string]TunnelStatus{ 14 Suspend.String(): Suspend, 15 Inner.String(): Inner, 16 Running.String(): Running, 17 } 18 19 const ( 20 Suspend TunnelStatus = iota 21 Inner 22 Running 23 ) 24 25 // UnmarshalJSON unserialize Status 26 func (s *TunnelStatus) UnmarshalJSON(data []byte) error { 27 var tp string 28 json.Unmarshal(data, &tp) 29 status, exist := StatusMapping[strings.ToLower(tp)] 30 if !exist { 31 return errors.New("invalid mode") 32 } 33 *s = status 34 return nil 35 } 36 37 // UnmarshalYAML unserialize Status with yaml 38 func (s *TunnelStatus) UnmarshalYAML(unmarshal func(any) error) error { 39 var tp string 40 unmarshal(&tp) 41 status, exist := StatusMapping[strings.ToLower(tp)] 42 if !exist { 43 return errors.New("invalid status") 44 } 45 *s = status 46 return nil 47 } 48 49 // MarshalJSON serialize Status 50 func (s TunnelStatus) MarshalJSON() ([]byte, error) { 51 return json.Marshal(s.String()) 52 } 53 54 // MarshalYAML serialize TunnelMode with yaml 55 func (s TunnelStatus) MarshalYAML() (any, error) { 56 return s.String(), nil 57 } 58 59 func (s TunnelStatus) String() string { 60 switch s { 61 case Suspend: 62 return "suspend" 63 case Inner: 64 return "inner" 65 case Running: 66 return "running" 67 default: 68 return "Unknown" 69 } 70 } 71 72 type AtomicStatus struct { 73 value atomic.Int32 74 } 75 76 func (a *AtomicStatus) Store(s TunnelStatus) { 77 a.value.Store(int32(s)) 78 } 79 80 func (a *AtomicStatus) Load() TunnelStatus { 81 return TunnelStatus(a.value.Load()) 82 } 83 84 func (a *AtomicStatus) String() string { 85 return a.Load().String() 86 } 87 88 func newAtomicStatus(s TunnelStatus) *AtomicStatus { 89 a := &AtomicStatus{} 90 a.Store(s) 91 return a 92 }