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.
- •Open the logic file.
- •Implement the business logic inside the
{{Handler}}method. - •Use
svcCtxto access DB/Cache/MQ (defined ininternal/svc/service_context.go). - •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.AddRoutesincludes the new handler. - •If using
main.go, ensurehandler.RegisterHandlersis called.
Templates Location
- •
templates/api.api.tmpl: Standard API definition template.
Reference
- •
references/: specific code patterns for handlers and logic.