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"}