SoFunction
Updated on 2025-03-03

How to create a RESTful API service to go-zero

In go-zero, creating a RESTful API service can be done throughgoctlThe 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.apiFile and usegoctlThe 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 newThe command can quickly generate a directory structure for a RESTful API project. For example, create a name calleduserServices:

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.apidocument

In go-zero,.apiFiles 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.apiIn the file:

UserRequestandUserResponseDefines the data structure of the request and response.service userDefines the name of the service.@handler CreateUserexpressCreateUserThe processor will process itPOST /api/v1/userrouting.

4. Use goctl to generate code

In the project root directory, usegoctlGenerate 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,CreateUserLogicis a business logic processor used for processingUserRequestRequest 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 usedcurlCommand 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.apidocument: Define API interfaces, data structures, requests, and responses.
  • Use goctl to generate code:usegoctl api goCommands 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-zerogoctlTools 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!