Skip to main content

Template

Template manipulationโ€‹

Template is the basis of data-driven generation, all code (rest api, rpc, model, docker, kube) generation will rely on template. By default, the template generator selects the in-memory template for generation, while for developers who need to modify the template, they need to drop the template and make template changes in the next code generation. For developers who need to modify the templates, they need to modify the templates, and then the next time the code is generated, it will load the templates under the specified path to generate.

Help for useโ€‹

NAME:
goctl template - template operation

USAGE:
goctl template command [command options] [arguments...]

COMMANDS:
init initialize the all templates(force update)
clean clean the all cache templates
update update template of the target category to the latest
revert revert the target template to the latest

OPTIONS:
--help, -h show help

Template initializationโ€‹

NAME:
goctl template init - initialize the all templates(force update)

USAGE:
goctl template init [command options] [arguments...]

OPTIONS:
--home value the goctl home path of the template

Clear templateโ€‹

NAME:
goctl template clean - clean the all cache templates

USAGE:
goctl template clean [command options] [arguments...]

OPTIONS:
--home value the goctl home path of the template

Roll back the specified category templateโ€‹

NAME:
goctl template update - update template of the target category to the latest

USAGE:
goctl template update [command options] [arguments...]

OPTIONS:
--category value, -c value the category of template, enum [api,rpc,model,docker,kube]
--home value the goctl home path of the template

Rollback templateโ€‹

NAME:
goctl template revert - revert the target template to the latest

USAGE:
goctl template revert [command options] [arguments...]

OPTIONS:
--category value, -c value the category of template, enum [api,rpc,model,docker,kube]
--name value, -n value the target file name of template
--home value the goctl home path of the template
tip

--home Specify the template storage path

Template loadingโ€‹

You can specify the folder where the template is located by -home during code generation, the commands that have been supported to specify the template directory are:

  • goctl api go Details can be found in goctl api go --help for help
  • goctl docker Details can be viewed with goctl docker --help
  • goctl kube Details can be viewed with goctl kube --help
  • goctl rpc new Details can be viewed with goctl rpc new --help
  • goctl rpc proto Details can be viewed with goctl rpc proto --help
  • goctl model mysql ddl Details can be viewed with goctl model mysql ddl --help
  • goctl model mysql datasource Details can be viewed with goctl model mysql datasource --help
  • goctl model postgresql datasource Details can be viewed with goctl model mysql datasource --help
  • goctl model mongo Details can be viewed with goctl model mongo --help

The default (when -home is not specified) is to read from the $HOME/.goctl directory.

Usage examplesโ€‹

  • Initialize the template to the specified $HOME/template directory
$ goctl template init --home $HOME/template 
Templates are generated in /Users/anqiansong/template, edit on your risk!
  • Greet rpc generation using $HOME/template template
$ goctl rpc new greet --home $HOME/template
Done

Template modificationโ€‹

Scenarioโ€‹

Implement a uniformly formatted body response in the following format:

{
"code": 0,
"msg": "OK",
"data": {} // โ‘ 
}

โ‘  Actual response 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 whose module is greet, with a directory tree similar to the following.

greet
โ”œโ”€โ”€ response
โ”‚ย ย  โ””โ”€โ”€ response.go
โ””โ”€โ”€ xxx...

The code is as follows:

package response

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"// โ‘ 
{% raw %}
{{.ImportPackages}}
{% endraw %}
)

{% raw %}
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}}response.Response(w, resp, err){{else}}response.Response(w, nil, err){{end}}//โ‘ก

}
}
{% endraw %}

โ‘  Replace with your real response package name, for reference only

โ‘ก Customize the template content

tip

If you don't have a ~/.goctl/api/handler.tpl file locally, you can initialize it with the template initialization command goctl template init

Comparison before and after modifying the templateโ€‹

  • Before modification
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)
// ไปฅไธ‹ๅ†…ๅฎนๅฐ†่ขซ่‡ชๅฎšไน‰ๆจกๆฟๆ›ฟๆข
if err != nil {
httpx.Error(w, err)
} else {
httpx.OkJson(w, resp)
}
}
}
  • After modification
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)
response.Response(w, resp, err)
}
}

Comparison of response body before and after template modificationโ€‹

  • Before modification
{
"message": "Hello go-zero!"
}
  • After modification
{
"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