paramify is a build-function generator tool based on the Functional Options Pattern, allowing you to build structs with intuitive, flexible, and type-safe APIs.
go install github.com/yukinagae/paramify/cmd/paramify@latestCreate a struct with the fields you need. Use struct tags to mark optional fields with omitempty.
//go:generate paramify -type=User
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Age uint `json:"age,omitempty"`
Address *Address `json:"address,omitempty"`
Friends []string `json:"friends,omitempty"`
}Run the following command to generate the necessary functions for building instances of your struct using the Functional Options Pattern.
$ go generateUse the generated functions to create instances of your struct. Required fields are passed as arguments to the constructor function, while optional fields are set using functional options.
func main() {
john := NewUser(
"1", // Required: ID
"John", // Required: Name
)
sam := NewUser(
"2", // Required: ID
"Sam", // Required: Name
WithUserAge(20), // Optional: Age
WithUserAddress(Address{"street"}), // Optional: Address
WithUserFriends([]string{"Jane"}), // Optional: Friends
)
}Here's a complete example demonstrating the usage:
package main
import "fmt"
//go:generate paramify -type=User
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Age uint `json:"age,omitempty"`
Address *Address `json:"address,omitempty"`
Friends []string `json:"friends,omitempty"`
}
type Address struct {
Street string `json:"street"`
}
func main() {
john := NewUser(
"1", // Required: ID
"John", // Required: Name
)
sam := NewUser(
"2", // Required: ID
"Sam", // Required: Name
WithUserAge(20), // Optional: Age
WithUserAddress(Address{"street"}), // Optional: Address
WithUserFriends([]string{"Jane"}), // Optional: Friends
)
fmt.Printf("%+v\n", john)
fmt.Printf("%+v\n", sam)
}We welcome contributions to this project! To get started, please refer to our Contribution Guide.
