Skip to content

Request Signing

In go-zero, HTTP services are declared in the api language and generated by goctl. For the complete api language reference, see the API DSL overview.

In go-zero we already have built-in signature features. We can enable signature by api language and then generate signature code by goctl, so we can use the signature function in the HTTP service.

In api language, we can start signing up with signature keyword, assuming we have a signdemo service, we have an interface below:

https://example.com/sign/demo

Its api language follows:

syntax = "v1"
type (
SignDemoReq {
Msg string `json:"msg"`
}
SignDemoResp {
Msg string `json:"msg"`
}
)
@server (
signature: true // 通过 signature 关键字开启签名功能
)
service sign-api {
@handler SignDemo
post /sign/demo (SignDemoReq) returns (SignDemoResp)
}

Let’s see the routing code generated. The full code can be downloaded here.

func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
server.AddRoutes(
[]rest.Route{
{
Method: http.MethodPost,
Path: "/sign/demo",
Handler: SignDemoHandler(serverCtx),
},
},
rest.WithSignature(serverCtx.Config.Signature),
)
}

It can be seen that we open the signature feature with res.WithSignature so we can use the signature feature in the HTTP service.