In go-zero, creating a RESTful API service can be done throughgoctl
The command is completed quickly. go-zero provides an efficient way to generate the project structure, routing, request and response models, and processing logic of services. These are defined.api
File and usegoctl
The tool generates code completed. Here are the steps to create a RESTful API service:
1. Install go-zero and goctl
Make sure the go-zero framework and its code generation tools are installedgoctl
。
go install /zeromicro/go-zero/tools/goctl@latest
2. Create a new API service project
usegoctl api new
The command can quickly generate a directory structure for a RESTful API project. For example, create a name calleduser
Services:
goctl api new user
This generates the following directory structure:
user/ ├── etc/ # Configuration File│ └── # API Service Configuration├── # API definition file├── # Go module file├── internal/ │ ├── config/ # Structure definition of configuration file│ │ └── │ ├── handler/ # HTTP Router Processor│ │ ├── │ │ └── #Route definition file│ ├── logic/ # Business Logic│ │ └── │ ├── svc/ # Service context│ │ └── │ └── types/ # Request and response data structure│ └── └── # Main program entry
3. Definition.api
document
In go-zero,.api
Files are used to define the interface, request parameters, response format and other information of the RESTful API. OpenFile, edit the following content:
syntax = "v1"; info( title: "User API" desc: "User service API" version: "1.0" ) type ( UserRequest { name string age int } UserResponse { id int name string age int } ) service user { @handler CreateUser post /api/v1/user (UserRequest) returns (UserResponse) }
In this.api
In the file:
UserRequest
andUserResponse
Defines the data structure of the request and response.service user
Defines the name of the service.@handler CreateUser
expressCreateUser
The processor will process itPOST /api/v1/user
routing.
4. Use goctl to generate code
In the project root directory, usegoctl
Generate code:
goctl api go -api -dir .
After execution, goctl will generate the following code:
-
handler
: Processor files containing routes. -
logic
: Contains business logic files. -
types
: A type file containing request and response.
Specifically, it will be generatedinternal/handler/
andinternal/logic/
document.
5. Implement business logic
Openinternal/logic/
File, implement business logic. Examples are as follows:
package logic import ( "context" "project-name/internal/svc" "project-name/internal/types" "/zeromicro/go-zero/core/logx" ) type CreateUserLogic struct { ctx svcCtx * } func NewCreateUserLogic(ctx , svcCtx *) *CreateUserLogic { return &CreateUserLogic{ Logger: (ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *CreateUserLogic) CreateUser(req *) (resp *, err error) { // Suppose the logic simply returns the requested content and appends an id resp = &{ id: 1, name: , age: , } return resp, nil }
In this example,CreateUserLogic
is a business logic processor used for processingUserRequest
Request and returnUserResponse
。
6. Configure routing
existinternal/handler/
In the file, goctl has generated the routing registration code. Make sure the route is configured correctly:
package handler import ( "net/http" "/zeromicro/go-zero/rest/httpx" "project-name/internal/logic" "project-name/internal/svc" "project-name/internal/types" ) func RegisterHandlers(svcCtx *) { ("/api/v1/user", func(w , r *) { var req if err := (r, &req); err != nil { (w, err) return } l := ((), svcCtx) resp, err := (&req) if err != nil { (w, err) } else { (w, resp) } }) }
7. Configure the service and start it
Openetc/
File, ports to configure RESTful service, etc.:
Name: user-api Host: 0.0.0.0 Port: 8080
Then, inStart the service in the file:
package main import ( "flag" "fmt" "project-name/internal/config" "project-name/internal/handler" "project-name/internal/svc" "/zeromicro/go-zero/core/conf" "/zeromicro/go-zero/rest" ) var configFile = ("f", "etc/", "the config file") func main() { () var c (*configFile, &c) server := () defer () ctx := (c) (ctx) ("Starting server at %s:%d...\n", , ) () }
8. Start the service and test it
Run the service in the project root directory:
go run -f etc/
After the service is started, it can be usedcurl
Command test:
curl -X POST -d '{"name":"Alice","age":25}' http://localhost:8080/api/v1/user
The return result should be similar to:
{ "id": 1, "name": "Alice", "age": 25 }
Summarize
-
definition
.api
document: Define API interfaces, data structures, requests, and responses. -
Use goctl to generate code:use
goctl api go
Commands generate routes, processors, and business logic files. - Implement business logic: Implement business logic in the generated logic file.
- Start the service and test it: Start the service and test it via HTTP request.
By go-zerogoctl
Tools that can quickly create RESTful API services, greatly improving development efficiency.
This is the article about go-zero's method of creating RESTful API services. For more related go-zero RESTful API services, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!