Skip to content

Instantly share code, notes, and snippets.

@17twenty
Last active July 14, 2020 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 17twenty/de6e064ed466427a3800c36ff10938d7 to your computer and use it in GitHub Desktop.
Save 17twenty/de6e064ed466427a3800c36ff10938d7 to your computer and use it in GitHub Desktop.
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)))))
}
@17twenty
Copy link
Author

pointer receivers are likely wrong 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment