Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
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.
- Host: GitHub
- URL: https://github.com/tomwright/structbuilder
- Owner: TomWright
- Created: 2024-09-12T17:09:50.000Z (2 months ago)
- Default Branch: main
- Last Pushed: 2024-09-24T17:22:13.000Z (about 2 months ago)
- Last Synced: 2024-10-11T01:03:56.877Z (about 1 month ago)
- Language: Go
- Size: 11.7 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
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=exampletype 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 buildersimport "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
}
}
```