/structbuilder

Go generator to create builders with options for your structs.

Primary LanguageGo

Struct Builder

Simple code generator to create builder functions with options for structs.

Installation

go install github.com/TomWright/structbuilder/cmd/structbuilder

Usage

Command

Simply run a go generate command:

go generate /path/to/module/github.com/TomWright/structbuilder/example/model.go

Source File

/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
}

Output

/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
	}
}