-
install goctl
GO111MODULE=on go get -u github.com/tal-tech/go-zero/tools/goctl
-
create the working dir
shorturl
andshorturl/api
-
in
shorturl
dir, executego mod init shorturl
to initializego.mod
-
use goctl to generate
api/shorturl.api
goctl api -o shorturl.api
for simplicity, the leading
info
block is removed, and the code looks like:type ( expandReq { shorten string `form:"shorten"` } expandResp { url string `json:"url"` } ) type ( shortenReq { url string `form:"url"` } shortenResp { shorten string `json:"shorten"` } ) service shorturl-api { @server( handler: ShortenHandler ) get /shorten(shortenReq) returns(shortenResp) @server( handler: ExpandHandler ) get /expand(expandReq) returns(expandResp) }
the usage of
type
keyword is the same as that in go, service is used to define get/post/head/delete api requests, described below:service shorturl-api {
defines the service name@server
defines the properties that used in server sidehandler
defines the handler nameget /shorten(shortenReq) returns(shortenResp)
defines this is a GET request, the request parameters, and the response parameters
-
generate the code for API Gateway by using goctl
goctl api go -api shorturl.api -dir .
the generated file structure looks like:
. ├── api │ ├── etc │ │ └── shorturl-api.yaml // configuration file │ ├── internal │ │ ├── config │ │ │ └── config.go // configuration definition │ │ ├── handler │ │ │ ├── expandhandler.go // implements expandHandler │ │ │ ├── routes.go // routes definition │ │ │ └── shortenhandler.go // implements shortenHandler │ │ ├── logic │ │ │ ├── expandlogic.go // implements ExpandLogic │ │ │ └── shortenlogic.go // implements ShortenLogic │ │ ├── svc │ │ │ └── servicecontext.go // defines ServiceContext │ │ └── types │ │ └── types.go // defines request/response │ ├── shorturl.api │ └── shorturl.go // main entrance ├── go.mod └── go.sum
-
start API Gateway service, listens on port 8888 by default
go run shorturl.go -f etc/shorturl-api.yaml
-
test API Gateway service
curl -i "http://localhost:8888/shorten?url=http://www.google.com"
response like:
HTTP/1.1 200 OK Content-Type: application/json Date: Thu, 27 Aug 2020 14:31:39 GMT Content-Length: 15 {"shortUrl":""}
You can see that the API Gateway service did nothing except returned a zero value.
-
you can modify
internal/svc/servicecontext.go
to pass dependencies if needed -
implement logic in package
internal/logic
-
you can use goctl to generate code for clients base on the .api file
-
till now, the client engineer can work with the api, don’t need to wait for the implementation of server side
goctl is a builtin tool in https://github.com/tal-tech/go-zero. Check out for more info.