{"id":34710950,"url":"https://github.com/zcyc/constructor","last_synced_at":"2026-05-27T05:35:30.939Z","repository":{"id":320972417,"uuid":"1083899311","full_name":"zcyc/constructor","owner":"zcyc","description":null,"archived":false,"fork":false,"pushed_at":"2025-10-27T02:08:40.000Z","size":40,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-10-27T04:10:58.380Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zcyc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-26T23:19:32.000Z","updated_at":"2025-10-27T02:08:44.000Z","dependencies_parsed_at":"2025-10-27T04:11:01.772Z","dependency_job_id":"a4077a2d-b4c6-4629-97c5-793f2c7fe522","html_url":"https://github.com/zcyc/constructor","commit_stats":null,"previous_names":["zcyc/constructor"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/zcyc/constructor","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zcyc%2Fconstructor","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zcyc%2Fconstructor/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zcyc%2Fconstructor/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zcyc%2Fconstructor/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zcyc","download_url":"https://codeload.github.com/zcyc/constructor/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zcyc%2Fconstructor/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33553127,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-05-27T02:00:06.184Z","response_time":53,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-12-24T23:56:58.112Z","updated_at":"2026-05-27T05:35:30.924Z","avatar_url":"https://github.com/zcyc.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Constructor\n\n[![Go Version](https://img.shields.io/badge/Go-%3E%3D%201.18-blue)](https://golang.org/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nA powerful Go code generator that creates constructor code for structs with support for multiple design patterns.\n\n## Features\n\n- 🚀 **Multiple Constructor Patterns**: Generate all args, builder, or functional options patterns\n- 🔧 **Flexible Configuration**: Customize output with various flags\n- 🏷️ **Field Tagging**: Fine-grained control with `constructor:\"-\"`, `constructor:\"getter:false\"`, and\n  `constructor:\"setter:false\"` tags\n- 🎯 **Initialization Support**: Call init methods after construction\n- 📦 **Value or Pointer**: Return values or pointers based on your needs\n- 🔍 **Getter Generation**: Automatically generate getter methods for private fields\n- 🛠️ **Import Management**: Automatic import handling via `goimports`\n\n## Installation\n\n```bash\ngo install github.com/zcyc/constructor@latest\n```\n\nOr download pre-built binaries from the [releases page](https://github.com/zcyc/constructor/releases).\n\n### Dependencies\n\nThis tool requires [goimports](https://pkg.go.dev/golang.org/x/tools/cmd/goimports) for automatic import management:\n\n```bash\ngo install golang.org/x/tools/cmd/goimports@latest\n```\n\n## Quick Start\n\n### 1. Add go:generate comment to your struct\n\n```go\npackage mypackage\n\nimport \"time\"\n\n//go:generate constructor -type=User -constructorTypes=allArgs,builder,options\ntype User struct {\n    id        int\n    name      string\n    email     string\n    createdAt time.Time\n    metadata  map[string]string `newc:\"-\"` // Skip this field\n}\n```\n\n### 2. Run go generate\n\n```bash\ngo generate ./...\n```\n\n### 3. Use the generated constructors\n\n```go\n// All args constructor\nuser1 := NewUser(1, \"Alice\", \"alice@example.com\", time.Now())\n\n// Builder pattern\nuser2 := NewUserBuilder().\n    Id(1).\n    Name(\"Bob\").\n    Email(\"bob@example.com\").\n    CreatedAt(time.Now()).\n    Build()\n\n// Functional options pattern\nuser3 := NewUserWithOptions(\n    WithId(1),\n    WithName(\"Charlie\"),\n    WithEmail(\"charlie@example.com\"),\n    WithCreatedAt(time.Now()),\n)\n```\n\n## Constructor Patterns\n\n### All Args Constructor\n\nGenerates a simple constructor that accepts all fields as parameters.\n\n```go\n//go:generate constructor -type=Config -constructorTypes=allArgs\ntype Config struct {\n    host string\n    port int\n}\n```\n\n**Generated code:**\n\n```go\nfunc NewConfig(host string, port int) *Config {\n    return \u0026Config{\n        host: host,\n        port: port,\n    }\n}\n```\n\n### Builder Pattern\n\nGenerates a builder struct with fluent setter methods.\n\n```go\n//go:generate constructor -type=Service -constructorTypes=builder -setterPrefix=With\ntype Service struct {\n    db     *sql.DB\n    cache  Cache\n    logger Logger\n}\n```\n\n**Generated code:**\n\n```go\ntype ServiceBuilder struct {\n    db     *sql.DB\n    cache  Cache\n    logger Logger\n}\n\nfunc NewServiceBuilder() *ServiceBuilder {\n    return \u0026ServiceBuilder{}\n}\n\nfunc (b *ServiceBuilder) WithDb(db *sql.DB) *ServiceBuilder {\n    b.db = db\n    return b\n}\n\n// ... other setters ...\n\nfunc (b *ServiceBuilder) Build() *Service {\n    return \u0026Service{\n        db:     b.db,\n        cache:  b.cache,\n        logger: b.logger,\n    }\n}\n```\n\n### Functional Options Pattern\n\nGenerates option functions for flexible configuration.\n\n```go\n//go:generate constructor -type=Server -constructorTypes=options\ntype Server struct {\n    host    string\n    port    int\n    timeout time.Duration\n}\n```\n\n**Generated code:**\n\n```go\ntype ServerOption func (*Server)\n\nfunc WithHost(host string) ServerOption {\n    return func (s *Server) {\n        s.host = host\n    }\n}\n\nfunc WithPort(port int) ServerOption {\n    return func (s *Server) {\n        s.port = port\n    }\n}\n\nfunc WithTimeout(timeout time.Duration) ServerOption {\n    return func (s *Server) {\n        s.timeout = timeout\n    }\n}\n\nfunc NewServerWithOptions(opts ...ServerOption) *Server {\n    v := \u0026Server{}\n    for _, opt := range opts {\n        opt(v)\n    }\n    return v\n}\n```\n\n## CLI Options\n\n```bash\nconstructor [flags]\n```\n\n### Flags\n\n| Flag                | Description                                 | Default         | Example                                     |\n|---------------------|---------------------------------------------|-----------------|---------------------------------------------|\n| `-type`             | **[Required]** Struct type name             | -               | `-type=User`                                |\n| `-constructorTypes` | Comma-separated list of patterns            | `allArgs`       | `-constructorTypes=allArgs,builder,options` |\n| `-output`           | Output file path                            | `\u003ctype\u003e_gen.go` | `-output=constructors.go`                   |\n| `-init`             | Init method name to call after construction | -               | `-init=initialize`                          |\n| `-returnValue`      | Return value instead of pointer             | `false`         | `-returnValue`                              |\n| `-setterPrefix`     | Prefix for builder setter methods           | -               | `-setterPrefix=With`                        |\n| `-withGetter`       | Generate getter methods for private fields  | `false`         | `-withGetter`                               |\n| `-version`          | Show version information                    | -               | `-version`                                  |\n\n## Advanced Usage\n\n### Initialization Function\n\nCall an initialization method after construction:\n\n```go\n//go:generate constructor -type=Service -constructorTypes=allArgs -init=initialize\ntype Service struct {\n    db     *sql.DB\n    logger Logger\n}\n\nfunc (s *Service) initialize() {\n    s.logger.Info(\"Service initialized\")\n}\n```\n\n**Generated:**\n\n```go\nfunc NewService(db *sql.DB, logger Logger) *Service {\n    v := \u0026Service{\n        db:     db,\n        logger: logger,\n    }\n    v.initialize()\n    return v\n}\n```\n\n### Return Value Instead of Pointer\n\n```go\n//go:generate constructor -type=Config -constructorTypes=allArgs -returnValue\ntype Config struct {\n    debug bool\n    port  int\n}\n```\n\n**Generated:**\n\n```go\nfunc NewConfig(debug bool, port int) Config {\n    return Config{\n        debug: debug,\n        port:  port,\n    }\n}\n```\n\n### Generate Getter Methods\n\n```go\n//go:generate constructor -type=Repository -constructorTypes=allArgs -withGetter\ntype Repository struct {\n    tableName string\n    db        *sql.DB\n}\n```\n\n**Generated:**\n\n```go\nfunc NewRepository(tableName string, db *sql.DB) *Repository {\n    return \u0026Repository{\n        tableName: tableName,\n        db:        db,\n    }\n}\n\nfunc (r *Repository) GetTableName() string {\n    return r.tableName\n}\n\nfunc (r *Repository) GetDb() *sql.DB {\n    return r.db\n}\n```\n\n### Field Control with Tags\n\nGoConstructor supports fine-grained control over field behavior using struct tags:\n\n#### Complete Skip\n\nSkip fields entirely (no constructor parameter, no getter):\n\n```go\n//go:generate constructor -type=User -constructorTypes=allArgs -withGetter\ntype User struct {\n    name     string\n    email    string\n    internal string `constructor:\"-\"` // Completely skipped\n}\n```\n\n**Generated:**\n\n```go\nfunc NewUser(name string, email string) *User {\n    return \u0026User{\n        name:  name,\n        email: email,\n    }\n}\n\nfunc (u *User) GetName() string {\n    return u.name\n}\n\nfunc (u *User) GetEmail() string {\n    return u.email\n}\n// No GetInternal() method\n```\n\n**Backward Compatibility:** Also supports `newc:\"-\"` and `gonstructor:\"-\"` tags.\n\n#### Skip Getter Only\n\nInclude field in constructor but don't generate getter:\n\n```go\n//go:generate constructor -type=Product -constructorTypes=allArgs -withGetter\ntype Product struct {\n    id          int\n    name        string\n    password    string `constructor:\"getter:false\"` // In constructor, but no getter\n}\n```\n\n**Generated:**\n\n```go\nfunc NewProduct(id int, name string, password string) *Product {\n    return \u0026Product{\n        id:       id,\n        name:     name,\n        password: password,\n    }\n}\n\nfunc (p *Product) GetId() int {\n    return p.id\n}\n\nfunc (p *Product) GetName() string {\n    return p.name\n}\n// No GetPassword() method (security sensitive)\n```\n\n#### Skip Setter Only\n\nGenerate getter but don't include in constructor:\n\n```go\n//go:generate constructor -type=Service -constructorTypes=builder -withGetter\ntype Service struct {\n    host        string\n    port        int\n    connCount   int `constructor:\"setter:false\"` // Has getter, but not in constructor\n}\n```\n\n**Generated:**\n\n```go\ntype ServiceBuilder struct {\n    host string\n    port int\n    // No connCount field\n}\n\nfunc (b *ServiceBuilder) Host(host string) *ServiceBuilder { ... }\nfunc (b *ServiceBuilder) Port(port int) *ServiceBuilder { ... }\n// No ConnCount() setter method\n\nfunc (s *Service) GetHost() string { return s.host }\nfunc (s *Service) GetPort() int { return s.port }\nfunc (s *Service) GetConnCount() int { return s.connCount } // Getter exists\n```\n\nThis is useful for fields that are managed internally but need to be read externally.\n\n### Builder with Setter Prefix\n\n```go\n//go:generate constructor -type=Client -constructorTypes=builder -setterPrefix=With\ntype Client struct {\n    host string\n    port int\n}\n```\n\n**Generated setter methods:**\n\n```go\nfunc (b *ClientBuilder) WithHost(host string) *ClientBuilder { ... }\nfunc (b *ClientBuilder) WithPort(port int) *ClientBuilder { ... }\n```\n\n### Multiple Patterns at Once\n\nGenerate multiple constructor patterns in a single file:\n\n```go\n//go:generate constructor -type=User -constructorTypes=allArgs,builder,options\ntype User struct {\n    name  string\n    email string\n}\n```\n\nThis generates all three patterns: `NewUser()`, `UserBuilder`, and `NewUserWithOptions()`.\n\n## Usage Without Installation\n\nFor team collaboration, you can run the generator without manual installation:\n\n```go\n//go:generate go run github.com/zcyc/constructor@latest -type=User -constructorTypes=allArgs\ntype User struct {\n    name string\n}\n```\n\nThis is especially useful in CI/CD pipelines and when working with teams where not everyone has the tool installed.\n\n## Comparison with Similar Tools\n\n### vs gonstructor\n\n- ✅ **Additional Pattern**: Functional options pattern support\n- ✅ **Cleaner Options**: More intuitive flag names\n- ✅ **Better Defaults**: Sensible defaults for common use cases\n- ✅ **Compatibility**: Supports `gonstructor:\"-\"` tags for migration\n\n### vs newc\n\n- ✅ **More Patterns**: Builder and functional options patterns\n- ✅ **More Options**: Setter prefix, getter generation, etc.\n- ✅ **Better Documentation**: Comprehensive examples and usage guide\n- ✅ **Compatibility**: Supports `newc:\"-\"` tags for migration\n\n## Examples\n\nCheck the [examples](./examples) directory for complete working examples organized by pattern:\n\n### All Args Pattern\n\n- `examples/allargs/user.go` - Basic all-args constructor with field skipping\n- `examples/allargs/product.go` - All-args with getter control\n\n### Builder Pattern\n\n- `examples/builder/service.go` - Builder with init function and setter prefix\n- `examples/builder/database.go` - Builder with fine-grained getter/setter control\n\n### Options Pattern\n\n- `examples/options/config.go` - Functional options with return value\n- `examples/options/server.go` - Options with getter/setter control\n\n### Mixed Patterns\n\n- `examples/mixed/repository.go` - All three patterns in one struct\n\nRun the demo:\n\n```bash\ncd examples/demo\ngo run main.go\n```\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request.\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -am 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Acknowledgments\n\n- [gonstructor](https://github.com/moznion/gonstructor) - Inspiration for builder pattern\n- [newc](https://github.com/Bin-Huang/newc) - Inspiration for clean API design\n- Go team for excellent AST parsing tools\n\n## Support\n\nIf you encounter any issues or have questions:\n\n1. Check the [examples](./examples) directory\n2. Search existing [issues](https://github.com/zcyc/constructor/issues)\n3. Create a new issue with detailed information\n\n---\n\n**Made with ❤️ for the Go community**\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzcyc%2Fconstructor","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzcyc%2Fconstructor","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzcyc%2Fconstructor/lists"}