Last active
March 24, 2025 01:09
-
Star
(106)
You must be signed in to star a gist -
Fork
(22)
You must be signed in to fork a gist
-
-
Save lummie/7f5c237a17853c031a57277371528e87 to your computer and use it in GitHub Desktop.
Golang Enum pattern that can be serialized to json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package enum_example | |
import ( | |
"bytes" | |
"encoding/json" | |
) | |
// TaskState represents the state of task, moving through Created, Running then Finished or Errorred | |
type TaskState int | |
const ( | |
// Created represents the task has been created but not started yet | |
Created TaskState = iota | |
//Running represents the task has started | |
Running | |
// Finished represents the task is complete | |
Finished | |
// Errorred represents the task has encountered a problem and is no longer running | |
Errorred | |
) | |
func (s TaskState) String() string { | |
return toString[s] | |
} | |
var toString = map[TaskState]string{ | |
Created: "Created", | |
Running: "Running", | |
Finished: "Finished", | |
Errorred: "Errorred", | |
} | |
var toID = map[string]TaskState{ | |
"Created": Created, | |
"Running": Running, | |
"Finished": Finished, | |
"Errorred": Errorred, | |
} | |
// MarshalJSON marshals the enum as a quoted json string | |
func (s TaskState) MarshalJSON() ([]byte, error) { | |
buffer := bytes.NewBufferString(`"`) | |
buffer.WriteString(toString[s]) | |
buffer.WriteString(`"`) | |
return buffer.Bytes(), nil | |
} | |
// UnmarshalJSON unmashals a quoted json string to the enum value | |
func (s *TaskState) UnmarshalJSON(b []byte) error { | |
var j string | |
err := json.Unmarshal(b, &j) | |
if err != nil { | |
return err | |
} | |
// Note that if the string cannot be found then it will be set to the zero value, 'Created' in this case. | |
*s = toID[j] | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I ran into an edge case today - you need to add the following method if you plan to unmarshal json into a map that uses a custom enum as a key (e.g.
map[TaskState]string
):Without it you will get an error like this when you unmarshal:
FWIW I found the docs on this confusing. The paragraph below from https://pkg.go.dev/encoding/json#Unmarshal seems to indicate that implementing
json.Unmarshaler
is sufficient (emphasis mine):However, this source code comment indicates otherwise: https://cs.opensource.google/go/go/+/refs/tags/go1.21.3:src/encoding/json/decode.go;drc=b9b8cecbfc72168ca03ad586cc2ed52b0e8db409;l=630