generate factory method utilities for golang.
- Go 1.11+
- make
$ go get -u github.com/akito0107/fm5/cmd/fm5
- You declare
struct
which has some member variables.
type Structure struct {
id int
name string
}
- Generate factory methods with passing the type name.
$ fm5 -t Structure
- Then, you can get file which named
Structure_fm.go
. This file contains the function which identifies whether given error is the one that we are defined before.
// Code generated by "fm5"; DO NOT EDIT.
package e2e
func NewStructure(id int, name string) *Structure {
return &Structure{id: id, name: name}
}
- You can also generate functional options pattern with
-fo
option.
$ fm5 -t Structure -fo
// Code generated by "fm5"; DO NOT EDIT.
package e2e
func NewStructure(id int, name string) *Structure {
return &Structure{id: id, name: name}
}
type StructureOption func(*Structure)
func NewStructureOptions(opts ...StructureOption) *Structure {
i := &Structure{}
for _, o := range opts {
o(i)
}
return i
}
func WithId(id int) StructureOption {
return func(i *Structure) {
i.id = id
}
}
func WithName(name string) StructureOption {
return func(i *Structure) {
i.name = name
}
}
- You can also customize return type with
-r
option. This feature convenient for returninginterface
type.
$ fm -t Structure -fo -r Interface
// Code generated by "fm5"; DO NOT EDIT.
package e2e
func NewStructure(id int, name string) Interface {
return &Structure{id: id, name: name}
}
type StructureOption func(*Structure)
func NewStructureOptions(opts ...StructureOption) Interface {
i := &Structure{}
for _, o := range opts {
o(i)
}
return i
}
func WithId(id int) StructureOption {
return func(i *Structure) {
i.id = id
}
}
func WithName(name string) StructureOption {
return func(i *Structure) {
i.name = name
}
}
$ fm5 --help
NAME:
fm5 - factory method generator
USAGE:
fm5 [OPTIONS]
VERSION:
0.0.0
COMMANDS:
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
--type value, -t value struct name (required)
--dryrun dryrun (default=false)
--factory-method, --fm generate default factory method(default=true)
--factory-method-name value, --fmn value factory method name(default=New + $typename)
--functional-option, --fo generate functional option patterns methods(default=false)
--functional-option-name value, --fon value functional option method name(New + $typename + Options)
--return-typename value, -r value return typename (if present, applied this type, otherwise, using pointer type of given type)
--help, -h show help
--version, -v print the version
This project is licensed under the Apache License 2.0 License - see the LICENSE file for details