Skip to content

brunolueders/go-builder-gen

Repository files navigation

Builder Code Generator for Go

Generates builders directly from your Go structs.

How to install

go install github.com/brunolueders/go-builder-gen@latest

How to use

Imagine you have the following User struct definition:

// file: /project/path/login/user.go
package login

/* ... */

type User struct {
    Name string
    Password []byte
    Roles map[string]Role
    Session *Session
}

To generate a builder for it, simply open a terminal and type:

go-builder-gen /project/path/login/user.go:User

This creates a user_builder.go file in the same package that looks like this:

// file: /project/path/login/user_builder.go
// Code generated by go-builder-gen. DO NOT EDIT.
package login

type UserBuilder struct {
    name string
    password []byte
    roles map[string]Role
    session *Session
}

func BuilderFromUser(user User) UserBuilder {
    return UserBuilder {
        name: user.Name,
        password: user.Password,
        roles: user.Roles,
        session: user.Session,
    }
}

func (builder UserBuilder) WithName(name string) UserBuilder {
    builder.name = name
    return builder
}

func (builder UserBuilder) WithPassword(password []byte) UserBuilder {
    builder.password = password
    return builder
}

func (builder UserBuilder) WithRoles(roles map[string]Role) UserBuilder {
    builder.roles = roles
    return builder
}

func (builder UserBuilder) WithSession(session *Session) UserBuilder {
    builder.session = session
    return builder
}

func (builder UserBuilder) Build() *User {
    return &User {
        Name: builder.name,
        Password: builder.password,
        Roles: builder.roles,
        Session: builder.session,
    }
}

How to configure

You can modify the way go-builder-gen treats each struct field using the builder struct tag. Currently, the only available flag is ignore, which directs go-builder-gen to omit the tagged field from the builder.

For example, when run on the Session struct below, go-builder-gen won't add a WithExpires method to the generated SessionBuilder type:

type Session struct {
    Token string
    Expires time.Time `builder:"ignore"`
}