codegen

package module
v0.1.20 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 15, 2026 License: MIT Imports: 6 Imported by: 0

README

GoREST Codegen Plugin

CI Go Report Card License

Code generation plugin for GoREST that automatically generates models, REST resources, DTOs, and OpenAPI schemas from your database schema.

Features

  • Model Generation: Generate Go structs from database tables with proper field types and JSON tags
  • Resource Generation: Create complete REST API handlers with CRUD operations
  • DTO Generation: Automatically generate Data Transfer Objects for API requests/responses
  • OpenAPI Schema: Generate OpenAPI 3.0 specification from your database schema
  • Multi-Database Support: Works with PostgreSQL, MySQL, and SQLite
  • Plugin Architecture: Integrates seamlessly with GoREST's plugin system

Installation

go get github.com/nicolasbonnici/gorest-codegen@latest

Usage

As a Plugin

Register the codegen plugin in your GoREST application:

import (
    "github.com/nicolasbonnici/gorest"
    codegenPlugin "github.com/nicolasbonnici/gorest-codegen"
    "github.com/nicolasbonnici/gorest/pluginloader"
)

func init() {
    pluginloader.RegisterPluginFactory("codegen", codegenPlugin.NewPlugin)
}

func main() {
    app := gorest.New()
    // ... configure your app ...
    app.Start()
}

Then enable it in your gorest.yaml:

plugins:
  - name: codegen
    enabled: true

The plugin will be initialized with access to your database and configuration, allowing you to invoke commands programmatically.

As a Standalone CLI

Build the standalone binary:

cd cmd/codegen
go build -o codegen

Run code generation commands:

# Generate models from database schema
./codegen models

# Generate REST resources and DTOs
./codegen resources

# Generate OpenAPI schema
./codegen openapi

# Run all generation steps
./codegen all
Using go run

You can also run it directly without building:

go run github.com/nicolasbonnici/gorest-codegen/cmd/codegen@latest all

Commands

models

Generates Go struct models from your database schema.

codegen models

Output location: generated/models/ (configurable in gorest.yaml)

resources

Generates REST API resource handlers and DTOs from your models.

codegen resources

Output location:

  • Resources: generated/resources/
  • DTOs: generated/dtos/
openapi

Generates OpenAPI 3.0 schema from your database schema.

codegen openapi

Output location: generated/openapi/schema.yaml

all

Runs all code generation steps in sequence.

codegen all

Configuration

Configure code generation in your gorest.yaml:

database:
  url: "postgres://user:pass@localhost:5432/mydb"

codegen:
  output:
    models: "generated/models"
    resources: "generated/resources"
    dtos: "generated/dtos"
    openapi: "generated/openapi"

  auth:
    enabled: true
    user_model: "User"
    identifier_field: "Email"
    password_field: "Password"

Example Workflow

  1. Design your database schema
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    firstname VARCHAR(100),
    lastname VARCHAR(100),
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE posts (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id),
    title VARCHAR(255) NOT NULL,
    content TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
  1. Run code generation
codegen all
  1. Generated files
generated/
├── models/
│   ├── user.go       # User model struct
│   └── post.go       # Post model struct
├── resources/
│   ├── user.go       # User REST handlers (List, Get, Create, Update, Delete)
│   ├── post.go       # Post REST handlers
│   └── routes.go     # Route registration
├── dtos/
│   ├── user.go       # User DTOs (CreateUserDTO, UpdateUserDTO)
│   └── post.go       # Post DTOs
└── openapi/
    └── schema.yaml   # OpenAPI 3.0 specification
  1. Use generated code in your app
import (
    "github.com/nicolasbonnici/gorest"
    "yourproject/generated/routes"
)

func main() {
    app := gorest.New()

    // Register generated routes
    routes.RegisterRoutes(app)

    app.Start()
}

Integration with Other Plugins

The codegen plugin can be used with other GoREST plugins like gorest-benchmark:

// In gorest-benchmark
import codegenPlugin "github.com/nicolasbonnici/gorest-codegen"

func (p *BenchmarkPlugin) Dependencies() []string {
    return []string{"codegen"}
}

// Access codegen via dependency injection
func (p *BenchmarkPlugin) Initialize(cfg map[string]any) error {
    if deps, ok := cfg[plugin.ConfigKeyDependencies]; ok {
        if depsMap, ok := deps.(map[string]plugin.Plugin); ok {
            p.codegenPlugin = depsMap["codegen"]
        }
    }
    return nil
}

Testing

Run the integration tests:

# Set up test database
export DATABASE_URL_TEST="postgres://postgres:postgres@localhost:5433/mydb_test?sslmode=disable"

# Run tests
go test -tags=integration ./codegen

Tests require a running database instance. The test suite supports PostgreSQL, MySQL, and SQLite.

Development

Building from Source
git clone https://github.com/nicolasbonnici/gorest-codegen.git
cd gorest-codegen
go mod download
go build ./...
Running Tests
# Unit tests (if any)
go test ./...

# Integration tests with PostgreSQL
DATABASE_URL_TEST="postgres://localhost/test" go test -tags=integration ./codegen

# Integration tests with SQLite
DATABASE_URL_TEST="sqlite::memory:" go test -tags=integration ./codegen

Requirements

  • Go 1.25.1 or later
  • GoREST v0.4.8 or later
  • Database (PostgreSQL, MySQL, or SQLite)

Development Environment

To set up your development environment:

make install

This will:

  • Install Go dependencies
  • Install development tools (golangci-lint)
  • Set up git hooks (pre-commit linting and tests)

Git Hooks

This directory contains git hooks for the GoREST plugin to maintain code quality.

Available Hooks
pre-commit

Runs before each commit to ensure code quality:

  • Linting: Runs make lint to check code style and potential issues
  • Tests: Runs make test to verify all tests pass
Installation
Automatic Installation

Run the install script from the project root:

./.githooks/install.sh
Manual Installation

Copy the hooks to your .git/hooks directory:

cp .githooks/pre-commit .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit

License

MIT License - see LICENSE file for details

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Support

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewPlugin

func NewPlugin() plugin.Plugin

NewPlugin creates a new instance of the codegen plugin

Types

type AllCommand

type AllCommand struct {
	// contains filtered or unexported fields
}

AllCommand runs all code generation steps

func (*AllCommand) Description

func (c *AllCommand) Description() string

func (*AllCommand) Name

func (c *AllCommand) Name() string

func (*AllCommand) Run

type CodegenPlugin

type CodegenPlugin struct {
	// contains filtered or unexported fields
}

CodegenPlugin implements the plugin.Plugin interface

func (*CodegenPlugin) Commands

func (p *CodegenPlugin) Commands() []plugin.Command

Commands returns the list of available commands

func (*CodegenPlugin) Handler

func (p *CodegenPlugin) Handler() fiber.Handler

Handler returns a no-op middleware handler (codegen is CLI-only)

func (*CodegenPlugin) Initialize

func (p *CodegenPlugin) Initialize(cfg map[string]any) error

Initialize initializes the plugin with configuration

func (*CodegenPlugin) Name

func (p *CodegenPlugin) Name() string

Name returns the plugin name

type ModelsCommand

type ModelsCommand struct {
	// contains filtered or unexported fields
}

ModelsCommand generates model structs from database schema

func (*ModelsCommand) Description

func (c *ModelsCommand) Description() string

func (*ModelsCommand) Name

func (c *ModelsCommand) Name() string

func (*ModelsCommand) Run

type OpenAPICommand

type OpenAPICommand struct {
	// contains filtered or unexported fields
}

OpenAPICommand generates OpenAPI schema file

func (*OpenAPICommand) Description

func (c *OpenAPICommand) Description() string

func (*OpenAPICommand) Name

func (c *OpenAPICommand) Name() string

func (*OpenAPICommand) Run

type ResourcesCommand

type ResourcesCommand struct {
	// contains filtered or unexported fields
}

ResourcesCommand generates REST API resources and DTOs from models

func (*ResourcesCommand) Description

func (c *ResourcesCommand) Description() string

func (*ResourcesCommand) Name

func (c *ResourcesCommand) Name() string

func (*ResourcesCommand) Run

Directories

Path Synopsis
cmd
codegen command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL