Skip to content

scaffold_en.md

maoxiaoyue edited this page May 14, 2026 · 1 revision

pkg/scaffold -- Smart Code Generation

The scaffold package provides cross-platform code generation functionality, automatically integrating Schema-first routes, Error Catalog, and Contract Testing. Supports Web, CLI, and Desktop project modes.

Supported Project Types

Type Creation Method UI Framework Use Case
Web hyp new myapp HypGo Router HTTP API, full-stack web applications
CLI hyp new cli mytool Cobra Command-line tools, Linux/Windows system utilities
Desktop hyp new desktop myapp Fyne Windows/Mac/Linux desktop applications (native GUI)

Web Project

Generate Controller

hyp generate controller user

Generates 4 files at once:

app/
├── controllers/user_controller.go   <- Handler logic (no route definitions)
├── routers/
│   ├── user.go                      <- Schema routes (Input/Output)
│   ├── router.go                    <- Setup() main entry point (first generation only)
│   └── middleware.go                <- Middleware configuration (first generation only)

Controller (app/controllers/user_controller.go):

  • Contains only handler methods (List, Create, Get, Update, Delete)
  • References models.CreateUserReq, models.UserResp as Input/Output
  • Predefined error codes (ErrUserNotFound, ErrUserInvalid)

Router (app/routers/user.go):

  • Schema-first route definitions
  • Each route carries Input/Output types, Summary, Tags, Responses
  • Automatically references controller and models

Generate Model

hyp generate model user

Generates 5 structs:

// DB model
type User struct { ... }

// Schema Input -- POST
type CreateUserReq struct {
    Name  string `json:"name"`
    Email string `json:"email"`
}

// Schema Input -- PUT
type UpdateUserReq struct { ... }

// Schema Output -- single item
type UserResp struct { ... }

// Schema Output -- list
type UserListResp struct {
    Data  []UserResp `json:"data"`
    Total int        `json:"total"`
}

Generate Service

hyp generate service user

Includes Error Catalog integration:

var ErrSvcUserNotFound = errors.Define("E_svc_user_001", 404, "User not found", "user")

Web Project Recommended Order

hyp generate model user          # 1. Define data structures first
hyp generate controller user     # 2. Generate handler + router
hyp generate service user        # 3. Generate business logic
# 4. Edit app/routers/router.go -> uncomment RegisterUserRoutes(r)
# 5. main.go -> routers.Setup(srv.Router())

CLI Project

v0.8.5+ CLI, Desktop, and gRPC project modes are new in v0.8.5. v0.8.1 supports Web projects only.

Create CLI Project

hyp new cli mytool

Generated structure:

mytool/
├── app/
│   ├── commands/
│   │   └── root.go        <- Cobra rootCmd
│   ├── models/            <- Shared: data structures
│   ├── services/          <- Shared: business logic
│   └── config/
│       └── config.yaml
├── main.go                <- commands.Execute()
└── go.mod

Generate CLI Subcommand

hyp generate command process
hyp generate command export

Each subcommand automatically:

  • Defines a *Cmd variable and run* function
  • Registers with rootCmd in init()
  • Includes default flag annotation examples

Generated code:

var processCmd = &cobra.Command{
    Use:   "process",
    Short: "Process command",
    RunE:  runProcess,
}

func init() {
    rootCmd.AddCommand(processCmd)
    // processCmd.Flags().StringP("input", "i", "", "Input file path")
}

func runProcess(cmd *cobra.Command, args []string) error {
    // TODO: implement process logic
    return nil
}

CLI Project Recommended Order

hyp new cli mytool                # 1. Create project
cd mytool && go mod tidy
hyp generate command process      # 2. Add subcommand
hyp generate command export       # 3. Add more subcommands
hyp generate model task           # 4. Shared data structures
hyp generate service worker       # 5. Shared business logic
go run .                          # 6. Run

Desktop Project (Fyne GUI)

v0.8.5+ Desktop project mode (Fyne GUI) is new in v0.8.5.

Create Desktop Project

hyp new desktop myapp

Generated structure:

myapp/
├── app/
│   ├── views/
│   │   └── main_view.go       <- Main view (Fyne widget + layout)
│   ├── models/                <- Shared: data structures
│   ├── services/              <- Shared: business logic
│   └── config/
│       └── config.yaml
├── main.go                    <- Fyne app.New() + window
└── go.mod                     <- Includes fyne.io/fyne/v2 dependency

Note: Fyne requires a C compiler (gcc) because CGO is a required dependency. On Windows, install MSYS2 or TDM-GCC.

Generate GUI View

hyp generate view settings
hyp generate view dashboard

Each view automatically includes:

  • fyne.Window parameter
  • container.NewVBox layout
  • widget.NewLabel + widget.NewSeparator basic structure

Generated code:

func SettingsView(w fyne.Window) fyne.CanvasObject {
    title := widget.NewLabel("Settings")
    title.TextStyle = fyne.TextStyle{Bold: true}

    // TODO: implement settings view layout

    return container.NewVBox(
        title,
        widget.NewSeparator(),
        widget.NewLabel("Settings view content goes here"),
    )
}

Desktop Project Recommended Order

hyp new desktop myapp            # 1. Create project
cd myapp && go mod tidy
hyp generate view settings       # 2. Add settings view
hyp generate view dashboard      # 3. Add dashboard
hyp generate model config        # 4. Shared data structures
hyp generate service storage     # 5. Shared business logic
go run .                         # 6. Run

Shared Components Across Three Project Types

Directory Web CLI Desktop Shared?
app/controllers/ Handler logic -- -- Web only
app/routers/ Schema routes -- -- Web only
app/commands/ -- Cobra subcommands -- CLI only
app/views/ -- -- Fyne GUI views Desktop only
app/models/ Data structures Data structures Data structures Shared across all three
app/services/ Business logic Business logic Business logic Shared across all three
app/config/ config.yaml config.yaml config.yaml Shared across all three

API Reference

Web Generation

scaffold.GenerateController(dir, name, moduleName string) error
scaffold.GenerateRouter(dir, name, moduleName string) error
scaffold.GenerateRouterSetup(dir, name, moduleName string) error
scaffold.GenerateMiddleware(dir string) error
scaffold.GenerateModel(dir, name string) error
scaffold.GenerateService(dir, name string) error

CLI Generation

scaffold.GenerateCLIProject(baseDir, name, moduleName string) error
scaffold.GenerateCommand(dir, name string) error

Desktop Generation

scaffold.GenerateDesktopProject(baseDir, name, moduleName string) error
scaffold.GenerateView(dir, name string) error

Security

  • Name validation: Only allows [a-zA-Z][a-zA-Z0-9_]* (prevents path traversal and code injection)
  • Length limit: Maximum 64 characters
  • Does not overwrite existing files (prevents accidental overwriting of manual modifications)
  • Module name auto-detected from go.mod

HypGo

繁體中文 | English


中文文件

設計文件

套件

AI 協作工具鏈

CLI 命令


English Docs

Design Docs

Packages

AI Collaboration Toolchain

CLI Commands

Clone this wiki locally