Skip to content

Commit

Permalink
Use string for command verb in json, so it is easier to read
Browse files Browse the repository at this point in the history
  • Loading branch information
jiegec committed Oct 9, 2020
1 parent 2a8fa56 commit 0375221
Showing 1 changed file with 40 additions and 14 deletions.
54 changes: 40 additions & 14 deletions internal/msg.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package internal

import (
"bytes"
"encoding/json"
"fmt"
"time"
)
Expand Down Expand Up @@ -60,21 +62,45 @@ const (
)

func (c CmdVerb) String() string {
switch c {
case CmdStart:
return "start"
case CmdStop:
return "stop"
case CmdDisable:
return "disable"
case CmdRestart:
return "restart"
case CmdPing:
return "ping"
case CmdReload:
return "reload"
mapping := map[CmdVerb]string{
CmdStart: "start",
CmdStop: "stop",
CmdDisable: "disable",
CmdRestart: "restart",
CmdPing: "ping",
CmdReload: "reload",
}
return "unknown"
return mapping[c]
}

func FromString(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 = FromString(j)
return nil
}

// A WorkerCmd is the command message send from the
Expand Down

0 comments on commit 0375221

Please sign in to comment.