Skip to main content

api demo code generation

Overview

After completing the goctl installation, we can create a minimal HTTP service to get an overview of goctl's go-zero api service.

Task Targets

  1. Learn how to create a minimized HTTP service using goctl
  2. Preliminary understanding of the project structure of go-zero

Preparing

  1. Complete golang installation
  2. Complete goctl installation

Code Generation

# Create workspaces and enter the directory
$ mkdir -p ~/workspace/api && cd ~/workspace/api
# Execute instructions generated demo service
$ goctl api new demo
Done.

After executing the instruction, a demo directory will be generated under the current directory that contains a minimized HTTP service and we will check the directory structure of the service.

$ cd ~/workspace/api/demo
$ ls
demo.api demo.go etc go.mod internal
$ tree
.
├── demo.api
├── demo.go
├── etc
│   └── demo-api.yaml
├── go.mod
└── internal
├── config
│   └── config.go
├── handler
│   ├── demohandler.go
│   └── routes.go
├── logic
│   └── demologic.go
├── svc
│   └── servicecontext.go
└── types
└── types.go
note

API, RPC, Job Directory structure is similar to what the go-zero project structure can look at Project Structure

Write simple logic code

After completing the above code generation, we can find ~/workspace/api/demo/internal/logic/demologic.go files, add codes between line 27 and 28 :

resp = new(types.Response)
resp.Message = req.Name

Start service

After writing the above code, we can start the service with the following instructions:

# Enter service directory
$ cd ~/workspace/api/demo
# to organize dependencies
$ go mod tidy
# Run go program
$ go run demo.go

When you see the following output Starting server at 0.0.0.0.0:888...indicates that the service has been successfully started, then we come to visit the HTTP service.

$ curl --request GET 'http://127.0.0.0.1:8888/from/me'

When you see the output in the terminal {"message":"me"} on behalf of your service successfully started.

When you come here following the steps in the document, congratulations, you have completed the creation and startup of the simplest go-zero api service. For instructions on using the goctl tool, please refer to "CLI Tools", for a complete description of the go-zero api service, please refer to 《HTTP Server》.