Use string for command verb in json, so it is easier to read

This commit is contained in:
Jiajie Chen 2020-10-10 00:37:34 +08:00
parent 2a8fa5636e
commit cd73602988

View File

@ -1,6 +1,8 @@
package internal package internal
import ( import (
"bytes"
"encoding/json"
"fmt" "fmt"
"time" "time"
) )
@ -60,21 +62,45 @@ const (
) )
func (c CmdVerb) String() string { func (c CmdVerb) String() string {
switch c { mapping := map[CmdVerb]string{
case CmdStart: CmdStart: "start",
return "start" CmdStop: "stop",
case CmdStop: CmdDisable: "disable",
return "stop" CmdRestart: "restart",
case CmdDisable: CmdPing: "ping",
return "disable" CmdReload: "reload",
case CmdRestart:
return "restart"
case CmdPing:
return "ping"
case CmdReload:
return "reload"
} }
return "unknown" return mapping[c]
}
func NewCmdVerbFromString(s string) CmdVerb {
mapping := map[string]CmdVerb{
"start": CmdStart,
"stop": CmdStop,
"disable": CmdDisable,
"restart": CmdRestart,
"ping": CmdPing,
"reload": CmdReload,
}
return mapping[s]
}
// Marshal and Unmarshal for CmdVerb
func (s CmdVerb) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
buffer.WriteString(s.String())
buffer.WriteString(`"`)
return buffer.Bytes(), nil
}
func (s *CmdVerb) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return err
}
*s = NewCmdVerbFromString(j)
return nil
} }
// A WorkerCmd is the command message send from the // A WorkerCmd is the command message send from the