Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/tomwright/structbuilder

Go generator to create builders with options for your structs.
https://github.com/tomwright/structbuilder

Last synced: 19 days ago
JSON representation

Go generator to create builders with options for your structs.

Awesome Lists containing this project

README

        

# Struct Builder

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

## Installation

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

## Usage

### Command
Simply run a go generate command:
```bash
go generate /path/to/module/github.com/TomWright/structbuilder/example/model.go
```

### Source File
`/path/to/module/github.com/TomWright/structbuilder/example/model.go`
```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`
```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`
```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
}
}
```