Simple code generator to create builder functions with options for structs.
go install github.com/TomWright/structbuilder/cmd/structbuilder
Simply run a go generate command:
go generate /path/to/module/github.com/TomWright/structbuilder/example/model.go
/path/to/module/github.com/TomWright/structbuilder/example/model.go
package example
// Generate the builder code in a different directory.
//go:generate structbuilder -target=User -source=model.go -destination=builders/model_builder.go -package=builders -source-package=github.com/TomWright/structbuilder/example
// Generate the builder code in this directory.
//go:generate structbuilder -target=User -source=model.go -destination=model_builder.go -package=example
type User struct {
Name string
}
/path/to/module/github.com/TomWright/structbuilder/example/model_builder.go
// Code generated by structbuilder. DO NOT EDIT.
package example
// BuildUserOption is a function that sets the given options on a User.
type BuildUserOption func(*User)
// BuildUser creates a new User with the given options.
func BuildUser(opts ...BuildUserOption) *User {
res := new(User)
for _, opt := range opts {
opt(res)
}
return res
}
// UserWithName sets Name to the given value.
func UserWithName(v string) BuildUserOption {
return func(u *User) {
u.Name = v
}
}
/path/to/module/github.com/TomWright/structbuilder/example/builders/model_builder.go
// Code generated by structbuilder. DO NOT EDIT.
package builders
import "github.com/TomWright/structbuilder/example"
// BuildUserOption is a function that sets the given options on a User.
type BuildUserOption func(*example.User)
// BuildUser creates a new User with the given options.
func BuildUser(opts ...BuildUserOption) *example.User {
res := new(example.User)
for _, opt := range opts {
opt(res)
}
return res
}
// UserWithName sets Name to the given value.
func UserWithName(v string) BuildUserOption {
return func(u *example.User) {
u.Name = v
}
}