Last active
July 14, 2020 06:13
-
-
Save 17twenty/de6e064ed466427a3800c36ff10938d7 to your computer and use it in GitHub Desktop.
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 {{.Package}} | |
import ( | |
"database/sql/driver" | |
"encoding/json" | |
"fmt" | |
"strings" | |
) | |
// {{.Type}}Enum is the status code of an {{.Type}} (must be int64) | |
type {{.Type}}Enum int64 | |
const ( | |
// {{.Type}}EnumUnknown is the default which means something is fucked up | |
{{.Type}}EnumUnknown {{.Type}}Enum = iota | |
) | |
func (x {{.Type}}Enum) String() string { | |
return map[{{.Type}}Enum]string{ | |
{{.Type}}EnumUnknown: "{{.Type}}EnumUnknown", | |
}[x] | |
} | |
// Scan is used for writing {{.Type}} to the database | |
func (x *{{.Type}}Enum) Scan(value interface{}) error { | |
db := value.([]uint8) | |
*x = map[string]{{.Type}}Enum{ | |
"{{.Type}}EnumUnknown": {{.Type}}EnumUnknown, | |
}[string(db)] | |
return nil | |
} | |
// Value is used for reading {{.Type}} from the database | |
func (x {{.Type}}Enum) Value() (driver.Value, error) { | |
return x.String(), nil | |
} | |
// MarshalJSON - custom marshal method to convert {{.Type}} to JSON | |
func (x *{{.Type}}Enum) MarshalJSON() ([]byte, error) { | |
return json.Marshal(strings.ReplaceAll(x.String(), "{{.Type}}", "")) | |
} | |
// UnmarshalJSON - custom unmarshal to convert string into {{.Type}}Enum | |
func (x *{{.Type}}Enum) UnmarshalJSON(b []byte) error { | |
var value string | |
err := json.Unmarshal(b, &value) | |
if err != nil { | |
return err | |
} | |
return x.Scan([]uint8((fmt.Sprintf("{{.Type}}%s", strings.Title(value))))) | |
} |
Author
17twenty
commented
Jul 14, 2020
- https://blog.carlmjohnson.net/post/2016-11-27-how-to-use-go-generate/
- https://github.com/golang/tools/blob/master/cmd/stringer/stringer.go
pointer receivers are likely wrong 🤔
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment