Create a gist now

Instantly share code, notes, and snippets.

@svett /main.go
Last active Sep 22, 2015

What would you like to do?
package main
//go:generate jsonenums -type=Status
type Status int
const (
Pending Status = iota
Sent
Received
Rejected
)
func main() {
status := Received
data, err := status.MarshalJSON()
if err != nil {
panic(err)
}
statusCopy := new(Status)
err = statusCopy.UnmarshalJSON(data)
if err != nil {
panic(err)
}
}
// generated by jsonenums -type=Status; DO NOT EDIT
package main
import (
"encoding/json"
"fmt"
)
var (
_StatusNameToValue = map[string]Status{
"Pending": Pending,
"Sent": Sent,
"Received": Received,
"Rejected": Rejected,
}
_StatusValueToName = map[Status]string{
Pending: "Pending",
Sent: "Sent",
Received: "Received",
Rejected: "Rejected",
}
)
func init() {
var v Status
if _, ok := interface{}(v).(fmt.Stringer); ok {
_StatusNameToValue = map[string]Status{
interface{}(Pending).(fmt.Stringer).String(): Pending,
interface{}(Sent).(fmt.Stringer).String(): Sent,
interface{}(Received).(fmt.Stringer).String(): Received,
interface{}(Rejected).(fmt.Stringer).String(): Rejected,
}
}
}
// MarshalJSON is generated so Status satisfies json.Marshaler.
func (r Status) MarshalJSON() ([]byte, error) {
if s, ok := interface{}(r).(fmt.Stringer); ok {
return json.Marshal(s.String())
}
s, ok := _StatusValueToName[r]
if !ok {
return nil, fmt.Errorf("invalid Status: %d", r)
}
return json.Marshal(s)
}
// UnmarshalJSON is generated so Status satisfies json.Unmarshaler.
func (r *Status) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return fmt.Errorf("Status should be a string, got %s", data)
}
v, ok := _StatusNameToValue[s]
if !ok {
return fmt.Errorf("invalid Status %q", s)
}
*r = v
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment