Template Modification

Scenario

Implement a uniformly formatted body accordingly, in the following format.

{
  "code": 0,
  "msg": "OK",
  "data": {}// ①
}

① 实际相应数据

[!TIP] The code generated by go-zero does not process it

Preparation

We go ahead and write a Response method in the response package under the project with module as greet, with a directory tree similar to the following.

greet
├── reponse
│   └── response.go
└── xxx...

The code is as follows

package reponse

import (
    "net/http"

    "github.com/tal-tech/go-zero/rest/httpx"
)

type Body struct {
    Code int         `json:"code"`
    Msg  string      `json:"msg"`
    Data interface{} `json:"data,omitempty"`
}

func Response(w http.ResponseWriter, resp interface{}, err error) {
    var body Body
    if err != nil {
        body.Code = -1
        body.Msg = err.Error()
    } else {
        body.Msg = "OK"
        body.Data = resp
    }
    httpx.OkJson(w, body)
}

Modify the handler template

$ vim ~/.goctl/api/handler.tpl

Replace the template with the following

package handler

import (
    "net/http"
    "greet/response"// ①

    {{.ImportPackages}}
)

func {{.HandlerName}}(ctx *svc.ServiceContext) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        {{if .HasRequest}}var req types.{{.RequestType}}
        if err := httpx.Parse(r, &req); err != nil {
            httpx.Error(w, err)
            return
        }{{end}}

        l := logic.New{{.LogicType}}(r.Context(), ctx)
        {{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}req{{end}})
        {{if .HasResp}}reponse.Response(w, resp, err){{else}}reponse.Response(w, nil, err){{end}}//②

    }
}

① Replace with your real response package name, for reference only

② Customized template content

[!TIP]

1.If there is no local ~/.goctl/api/handler.tpl file, you can initialize it with the template initialization command goctl template init

Comparison

  • Before

    func GreetHandler(ctx *svc.ServiceContext) http.HandlerFunc {
      return func(w http.ResponseWriter, r *http.Request) {
          var req types.Request
          if err := httpx.Parse(r, &req); err != nil {
              httpx.Error(w, err)
              return
          }
    
          l := logic.NewGreetLogic(r.Context(), ctx)
          resp, err := l.Greet(req)
          // The following content will be replaced by custom templates
          if err != nil {
              httpx.Error(w, err)
          } else {
              httpx.OkJson(w, resp)
          }
      }
    }
    
  • After

    func GreetHandler(ctx *svc.ServiceContext) http.HandlerFunc {
      return func(w http.ResponseWriter, r *http.Request) {
          var req types.Request
          if err := httpx.Parse(r, &req); err != nil {
              httpx.Error(w, err)
              return
          }
    
          l := logic.NewGreetLogic(r.Context(), ctx)
          resp, err := l.Greet(req)
          reponse.Response(w, resp, err)
      }
    }
    

Comparison of response body

  • Before

    {
      "message": "Hello go-zero!"
    }
    
  • After

    {
      "code": 0,
      "msg": "OK",
      "data": {
          "message": "Hello go-zero!"
      }
    }
    

Summary

This document only describes the process of customizing the template for the corresponding example of http, in addition to the following scenarios of customizing the template.

  • model layer adds kmq
  • model layer to generate the model instance of the option to be valid
  • http customize the corresponding format ...
Copyright © 2019-2021 go-zero all right reserved,powered by GitbookLast UpdateTime: 2021-12-05 09:48:50

results matching ""

    No results matching ""