Skip to main content

Build API

Create greet service​

$ cd ~/go-zero-demo
$ go mod init go-zero-demo
$ goctl api new greet
Done.

Take a look at the structure of the greet service

$ cd greet
$ tree
.
β”œβ”€β”€ etc
β”‚Β Β  └── greet-api.yaml
β”œβ”€β”€ greet.api
β”œβ”€β”€ greet.go
└── internal
β”œβ”€β”€ config
β”‚Β Β  └── config.go
β”œβ”€β”€ handler
β”‚Β Β  β”œβ”€β”€ greethandler.go
β”‚Β Β  └── routes.go
β”œβ”€β”€ logic
β”‚Β Β  └── greetlogic.go
β”œβ”€β”€ svc
β”‚Β Β  └── servicecontext.go
└── types
└── types.go

As you can see from the above directory structure, the greet service is small, but it has all the "guts". Next we can write the business code in greetlogic.go.

Writing logic​

$ vim ~/go-zero-demo/greet/internal/logic/greetlogic.go 
func (l *GreetLogic) Greet(req types.Request) (*types.Response, error) {
return &types.Response{
Message: "Hello go-zero",
}, nil
}

Start and access the service​

  • Start-up services
$ cd ~/go-zero-demo/greet
$ go run greet.go -f etc/greet-api.yaml
Starting server at 0.0.0.0:8888...
  • Access services
$ curl -i -X GET \
http://localhost:8888/from/you
HTTP/1.1 200 OK
Content-Type: application/json
Date: Sun, 07 Feb 2021 04:31:25 GMT
Content-Length: 27

{"message":"Hello go-zero"}

Source Code​

greet source code