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

  1. # Create workspaces and enter the directory
  2. $ mkdir -p ~/workspace/api && cd ~/workspace/api
  3. # Execute instructions generated demo service
  4. $ goctl api new demo
  5. 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.

  1. $ cd ~/workspace/api/demo
  2. $ ls
  3. demo.api demo.go etc go.mod internal
  4. $ tree
  5. .
  6. ├── demo.api
  7. ├── demo.go
  8. ├── etc
  9. └── demo-api.yaml
  10. ├── go.mod
  11. └── internal
  12. ├── config
  13. └── config.go
  14. ├── handler
  15. ├── demohandler.go
  16. └── routes.go
  17. ├── logic
  18. └── demologic.go
  19. ├── svc
  20. └── servicecontext.go
  21. └── types
  22. └── types.go
api demo code generation - 图1note

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 c odes between line 27 and 28 :

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

Start service

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

  1. # Enter service directory
  2. $ cd ~/workspace/api/demo
  3. # to organize dependencies
  4. $ go mod tidy
  5. # Run go program
  6. $ 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.

  • 终端中访问
  • Postman 中访问
  1. $ 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.

postman

Access in Postman

The service on your behalf has been successfully launched when you see the following output in Postman.

  1. {
  2. "message": "me"
  3. }

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