[ go-zero自定义模板 ]


自定义模板

routes.tpl

// Code generated by goctl. DO NOT EDIT.
package handler

import (
    "context"
    "strings"
    "time"
    "go-weixin/app/usercenter/userrpc/pb/proto/usercenter"
    "net/http"{{if .hasTimeout}}
    "time"{{end}}

    "go/types"
    "github.com/zeromicro/go-zero/core/logx"
    xhttp "github.com/zeromicro/x/http"
    "github.com/zeromicro/go-zero/rest/httpx"
    "github.com/zeromicro/x/errors"

    {{.importPackages}}
)

func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
    server.Use(serverCtx.ApiMDLE.AuthMiddleware)
    {{.routesAdditions}}
    // api异常捕获
    httpx.SetErrorHandler(func(err error) (int, any) {
        switch e := err.(type) {
        case *errors.CodeMsg:
            return http.StatusOK, xhttp.BaseResponse[types.Nil]{
                Code: e.Code,
                Msg:  e.Msg,
            }
        default:
            return http.StatusInternalServerError, nil
        }
    })
    // 所有接口路径添加到数据库表里
    for _, r := range server.Routes() {
        url := r.Path
        name := strings.Split(url, "/")[1]
        ctx, cannFunc := context.WithTimeout(context.Background(), 5*time.Second)
        defer cannFunc()
        _, err := serverCtx.UserRpc.TableAdd(ctx, &usercenter.TableAddReq{
            Name: name,
            Url: url,
            Method: 0,
        })
        if err != nil {
            logx.Error(err)
        }
    }
}

handler.tpl

package {{.PkgName}}

import (
    "net/http"

    "github.com/zeromicro/go-zero/rest/httpx"
    xhttp "github.com/zeromicro/x/http"
    "github.com/zeromicro/x/errors"
    {{.ImportPackages}}
)

func {{.HandlerName}}(svcCtx *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.ErrorCtx(r.Context(), w, errors.New(2000, err.Error()))
            return
        }

        {{end}}l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx)
        {{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}&req{{end}})
        if err != nil {
            xhttp.JsonBaseResponseCtx(r.Context(), w, err)
        } else {
            xhttp.JsonBaseResponseCtx(r.Context(), w, resp)
        }
    }
}