Template Modification

    ① 实际相应数据

    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.

    1. greet
    2. ├── reponse
    3. └── response.go
    4. └── xxx...

    The code is as follows

    1. package reponse
    2. import (
    3. "net/http"
    4. "github.com/tal-tech/go-zero/rest/httpx"
    5. )
    6. type Body struct {
    7. Code int `json:"code"`
    8. Msg string `json:"msg"`
    9. Data interface{} `json:"data,omitempty"`
    10. }
    11. func Response(w http.ResponseWriter, resp interface{}, err error) {
    12. var body Body
    13. if err != nil {
    14. body.Code = -1
    15. body.Msg = err.Error()
    16. } else {
    17. body.Data = resp
    18. }
    19. httpx.OkJson(w, body)
    20. }
    1. package handler
    2. import (
    3. "net/http"
    4. "greet/response"// ①
    5. {{.ImportPackages}}
    6. )
    7. func {{.HandlerName}}(ctx *svc.ServiceContext) http.HandlerFunc {
    8. return func(w http.ResponseWriter, r *http.Request) {
    9. {{if .HasRequest}}var req types.{{.RequestType}}
    10. if err := httpx.Parse(r, &req); err != nil {
    11. httpx.Error(w, err)
    12. return
    13. }{{end}}
    14. l := logic.New{{.LogicType}}(r.Context(), ctx)
    15. {{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}req{{end}})
    16. {{if .HasResp}}reponse.Response(w, resp, err){{else}}reponse.Response(w, nil, err){{end}}//②
    17. }
    18. }

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

    ② Customized template content

    [!TIP]

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

      1. func GreetHandler(ctx *svc.ServiceContext) http.HandlerFunc {
      2. return func(w http.ResponseWriter, r *http.Request) {
      3. if err := httpx.Parse(r, &req); err != nil {
      4. httpx.Error(w, err)
      5. return
      6. }
      7. l := logic.NewGreetLogic(r.Context(), ctx)
      8. resp, err := l.Greet(req)
      9. // The following content will be replaced by custom templates
      10. if err != nil {
      11. httpx.Error(w, err)
      12. } else {
      13. httpx.OkJson(w, resp)
      14. }
      15. }
      16. }
    • After

    • Before

      1. {
      2. "message": "Hello go-zero!"
      3. }
    • After

      1. {
      2. "code": 0,
      3. "msg": "OK",
      4. "data": {
      5. "message": "Hello go-zero!"
      6. }
      7. }

    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