go-enum-codegen
go-enum-codegen
is a command-line tool that generates methods to satisfy json.Marshaler
, json.Unmarshaler
, sql.Scanner
, & driver.Valuer
interfaces for common enum patterns.
With the default settings and given a type MyEnum
that is a string or integer type, go-enum-codegen
will create a new self-contained Go source file implementing:
// myenum.gen.go
// Code generated by "go-enum-codegen -type MyEnum"; DO NOT EDIT
package mypackage
func (t MyEnum) MarshalJSON() ([]byte, error) {
...
}
func (t *MyEnum) UnmarshalJSON(data []byte) error {
...
}
func (t MyEnum) Value() (driver.Value, error) {
...
}
func (t *MyEnum) Scan(v any) error {
...
}
Installation
go-enum-codegen
can be installed using the recommended tools.go
pattern
so it can be managed alongside the rest of your module.
To do so, create a file called tools/tools.go
at the root of your module with the following contents:
//go:build tools
// +build tools
package main
import (
_ "github.com/ejfrick/go-enum-codegen/cmd/go-enum-codegen"
)
Then, you can invoke go-enum-codegen
like so:
//go:generate go run github.com/ejfrick/go-enum-codegen/cmd/go-enum-codegen -type MyEnum
go-enum-codegen
can alternatively be installed as a binary:
$ go install github.com/ejfrick/go-enum-codegen/cmd/go-enum-codegen@latest
$ go-enum-codegen -version
When installed as a binary, it would be invoked as follows:
//go:generate go-enum-codegen -type MyEnum
Usage
Usage of go-enum-codegen:
-e
same as -error-on-unknown
-error-on-unknown
whether to return an error if scanning or unmarshalling an unknown value; automatically set to true when iota is first set to "_" or there is no enum equal to the empty value of its underlying type; otherwise default is false and an unknown value will be assigned to the enum with the empty value of its underlying type
-h
same as -help.
-help
show this help and exit
-json
generate only json.Marshaler and json.Unmarshaler methods; default false
-output string
output file name; default srcdir/<type>.gen.go
-sql
generate only sql.Scanner and driver.Value methods; default false
-stringer
use the String() method of the enum instead of the underlying integer value; default false
-tags string
comma-separated list of build tags to apply
-type string
comma-separated list of type names; must be set
-version
show version and exit
Examples
You can find examples for several different scenarios in the examples directory
To-Do
- Homebrew formula
- More tests
- More docs
Feature Requests, Bug Reports, Contributing, Etc.
Please open an issue (or a pull request!)