Last active
September 22, 2015 11:53
-
-
Save iamralch/0053bab033a581f7675a to your computer and use it in GitHub Desktop.
Example of using https://github.com/campoy/jsonenums
This file contains 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 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) | |
} | |
} |
This file contains 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
// 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