AgentSkillsCN

go-zero-api-skill

利用此技能开发或扩展Go-Zero REST API。该技能可指导用户使用标准模板创建.api文件,借助goctl生成代码,并实现处理器与业务逻辑。触发条件包括:“创建API”“添加端点”“生成Go-Zero API”。

SKILL.md
--- frontmatter
name: go-zero-api-skill
description: Use this skill to develop or extend go-zero REST APIs. It guides the creation of .api files using standard templates, generating code with goctl, and implementing handlers/logic. Triggers: "create api", "add endpoint", "generate go-zero api".

Go Zero API Development

This skill guides the AI to develop REST APIs using the go-zero framework standard workflow: Define API -> Generate Code -> Implement Logic.

Execution Steps

Step 1: Create/Update API Definition

If this is a new service, create a new .api file using the template. If adding to an existing service, append to the relevant .api file.

Template Usage:

  • Source: templates/api.api.tmpl
  • Target: api/{{SERVICE_NAME}}.api (or specific module api file)
  • Variables:
    • {{SERVICE_NAME}}: Service name (e.g., user)
    • {{GROUP_NAME}}: Handler group (e.g., user)
    • {{HANDLER_NAME}}: Handler name (e.g., GetUser)
    • {{URL_PATH}}: URL path (e.g., info)

Step 2: Generate Code (goctl)

Run the goctl command to generate the Go code (handlers, types, logic, routes) from the .api file.

bash
# General command pattern
goctl api go -api {{API_FILE_PATH}} -dir {{OUTPUT_DIR}} -style gozero

Example:

bash
# Assuming you are in the project root and the api file is api/user.api
goctl api go -api api/user.api -dir api/ -style gozero

Step 3: Implement Business Logic

After generation, goctl creates internal/logic/{{GROUP}}/{{HANDLER}}logic.go.

  1. Open the logic file.
  2. Implement the business logic inside the {{Handler}} method.
  3. Use svcCtx to access DB/Cache/MQ (defined in internal/svc/service_context.go).
  4. Return the response defined in types.

Step 4: Register Routes (If needed)

Usually goctl auto-generates route registration in internal/handler/routes.go.

  • Check if server.AddRoutes includes the new handler.
  • If using main.go, ensure handler.RegisterHandlers is called.

Templates Location

  • templates/api.api.tmpl: Standard API definition template.

Reference

  • references/: specific code patterns for handlers and logic.