Coordinator Role: json marshaling as string

This commit is contained in:
Malte Poll 2022-04-11 10:31:10 +02:00 committed by Malte Poll
parent 0f35a9a5c2
commit af1aca4b34
2 changed files with 124 additions and 0 deletions

View file

@ -1,5 +1,10 @@
package role
import (
"encoding/json"
"strings"
)
//go:generate stringer -type=Role
// Role is a peer's role.
@ -10,3 +15,26 @@ const (
Coordinator
Node
)
// MarshalJSON marshals the Role to JSON string.
func (r Role) MarshalJSON() ([]byte, error) {
return json.Marshal(r.String())
}
// UnmarshalJSON unmarshals the Role from JSON string.
func (r *Role) UnmarshalJSON(b []byte) error {
var roleString string
if err := json.Unmarshal(b, &roleString); err != nil {
return err
}
switch strings.ToLower(roleString) {
case "coordinator":
*r = Coordinator
case "node":
*r = Node
default:
*r = Unknown
}
return nil
}