Signature switch

Overview

In go-zero, we declared HTTP service via api language, and then generated HTTP service code via goctl, after our systematic introduction to API norm.

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.

Signature switch

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

  1. https://example.com/sign/demo

Its api language follows:

  1. syntax = "v1"
  2. type (
  3. SignDemoReq {
  4. Msg string `json:"msg"`
  5. }
  6. SignDemoResp {
  7. Msg string `json:"msg"`
  8. }
  9. )
  10. @server (
  11. signature: true // 通过 signature 关键字开启签名功能
  12. )
  13. service sign-api {
  14. @handler SignDemo
  15. post /sign/demo (SignDemoReq) returns (SignDemoResp)
  16. }

Let’s see the routing code generated, the full code click to download it here

  1. func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
  2. server.AddRoutes(
  3. []rest.Route{
  4. {
  5. Method: http.MethodPost,
  6. Path: "/sign/demo",
  7. Handler: SignDemoHandler(serverCtx),
  8. },
  9. },
  10. rest.WithSignature(serverCtx.Config.Signature),
  11. )
  12. }

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