1
0
mirror of https://github.com/MetaCubeX/mihomo.git synced 2025-09-19 20:15:59 +08:00

chore: some internal types support encoding.TextUnmarshaler

This commit is contained in:
wwqgtxx
2024-09-19 18:06:36 +08:00
parent 794645b7f8
commit a08aa10630
5 changed files with 129 additions and 39 deletions

View File

@ -3,6 +3,7 @@ package log
import (
"encoding/json"
"errors"
"strings"
)
// LogLevelMapping is a mapping for LogLevel enum
@ -28,7 +29,7 @@ type LogLevel int
func (l *LogLevel) UnmarshalYAML(unmarshal func(any) error) error {
var tp string
unmarshal(&tp)
level, exist := LogLevelMapping[tp]
level, exist := LogLevelMapping[strings.ToLower(tp)]
if !exist {
return errors.New("invalid mode")
}
@ -40,7 +41,7 @@ func (l *LogLevel) UnmarshalYAML(unmarshal func(any) error) error {
func (l *LogLevel) UnmarshalJSON(data []byte) error {
var tp string
json.Unmarshal(data, &tp)
level, exist := LogLevelMapping[tp]
level, exist := LogLevelMapping[strings.ToLower(tp)]
if !exist {
return errors.New("invalid mode")
}
@ -48,9 +49,14 @@ func (l *LogLevel) UnmarshalJSON(data []byte) error {
return nil
}
// MarshalJSON serialize LogLevel with json
func (l LogLevel) MarshalJSON() ([]byte, error) {
return json.Marshal(l.String())
// UnmarshalText unserialize LogLevel
func (l *LogLevel) UnmarshalText(data []byte) error {
level, exist := LogLevelMapping[strings.ToLower(string(data))]
if !exist {
return errors.New("invalid mode")
}
*l = level
return nil
}
// MarshalYAML serialize LogLevel with yaml
@ -58,6 +64,16 @@ func (l LogLevel) MarshalYAML() (any, error) {
return l.String(), nil
}
// MarshalJSON serialize LogLevel with json
func (l LogLevel) MarshalJSON() ([]byte, error) {
return json.Marshal(l.String())
}
// MarshalText serialize LogLevel
func (l LogLevel) MarshalText() ([]byte, error) {
return []byte(l.String()), nil
}
func (l LogLevel) String() string {
switch l {
case INFO: