Add role.FromString and more tolerance

This commit is contained in:
katexochen 2022-10-06 11:57:35 +02:00 committed by Paul Meyer
parent f4af9c56f5
commit 75888e986e
2 changed files with 7 additions and 12 deletions

View File

@ -34,23 +34,14 @@ func (r *Role) UnmarshalJSON(b []byte) error {
if err := json.Unmarshal(b, &roleString); err != nil { if err := json.Unmarshal(b, &roleString); err != nil {
return err return err
} }
switch strings.ToLower(roleString) { *r = FromString(roleString)
case "controlplane":
*r = ControlPlane
case "worker":
*r = Worker
case "admin":
*r = Admin
default:
*r = Unknown
}
return nil return nil
} }
// FromString converts a string to a Role. // FromString returns the Role for the given string.
func FromString(s string) Role { func FromString(s string) Role {
switch strings.ToLower(s) { switch strings.ToLower(s) {
case "controlplane": case "controlplane", "control-plane":
return ControlPlane return ControlPlane
case "worker": case "worker":
return Worker return Worker

View File

@ -69,6 +69,10 @@ func TestUnmarshal(t *testing.T) {
json: `"ControlPlane"`, json: `"ControlPlane"`,
wantRole: ControlPlane, wantRole: ControlPlane,
}, },
"dashed ControlPlane can be unmarshaled": {
json: `"Control-Plane"`,
wantRole: ControlPlane,
},
"lowercase controlPlane can be unmarshaled": { "lowercase controlPlane can be unmarshaled": {
json: `"controlPlane"`, json: `"controlPlane"`,
wantRole: ControlPlane, wantRole: ControlPlane,