Categorygithub.com/yukinagae/paramify
modulepackage
0.3.1
Repository: https://github.com/yukinagae/paramify.git
Documentation: pkg.go.dev

# README

Gopher Build

paramify

Go Reference Go Report Card GitHub License

Github version Static Badge
GitHub Issues or Pull Requests GitHub Issues or Pull Requests GitHub commit activity

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.

Installation

go install github.com/yukinagae/paramify@latest

Usage

Create 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 generate

Use 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
	)
}

Example

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

Contributing

We welcome contributions to this project! To get started, please refer to our Contribution Guide.

# Packages

Code generated by paramify -type=Params; DO NOT EDIT.
No description provided by the author