├── 1.3.4.zip ├── README.md ├── api ├── config.tpl ├── context.tpl ├── etc.tpl ├── handler.tpl ├── logic.tpl ├── main.tpl ├── middleware.tpl ├── route-addition.tpl ├── routes.tpl ├── template.tpl └── types.tpl ├── docker └── docker.tpl ├── goctl-v1.3.8-windows-amd64_2.zip ├── goctl-v1.4.0-windows-amd64.zip ├── kube ├── deployment.tpl └── job.tpl ├── model ├── delete.tpl ├── err.tpl ├── field.tpl ├── find-one-by-field-extra-method.tpl ├── find-one-by-field.tpl ├── find-one.tpl ├── import-no-cache.tpl ├── import.tpl ├── insert.tpl ├── interface-delete.tpl ├── interface-find-one-by-field.tpl ├── interface-find-one.tpl ├── interface-insert.tpl ├── interface-update.tpl ├── model-gen.tpl ├── model-new.tpl ├── model.tpl ├── table-name.tpl ├── tag.tpl ├── types.tpl ├── update.tpl └── var.tpl ├── mongo ├── err.tpl └── model.tpl ├── newapi └── newtemplate.tpl └── rpc ├── call-func.tpl ├── call-interface-func.tpl ├── call.tpl ├── config.tpl ├── etc.tpl ├── logic-func.tpl ├── logic.tpl ├── logic.tpl_1.3.8 ├── logic.tpl_1.4.0 ├── main.tpl ├── main.tpl_1.3.8 ├── main.tpl_1.4.0 ├── server-func.tpl ├── server-func.tpl_1.3.8 ├── server-func.tpl_1.4.0 ├── server.tpl ├── svc.tpl └── template.tpl /1.3.4.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/21888/goctl-template/a4595aa98f1c5473d4aa7a8bcc747c5358e66cb5/1.3.4.zip -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## goctl-template 2 | 3 | ### goctl go-zero 拓展模板 4 | 5 | 6 | 需要配合我修改的goctl生成代码 https://github.com/21888/goctl-chabai 7 | 8 | model 增加了一些查询删除操作 9 | rpc 会自动生成增删改查的示例代码,因为不想动model sql改的频繁 所以就把业务逻辑的操作尽可能的堆积在rpc了 后面可能会优化下model的生成 -------------------------------------------------------------------------------- /api/config.tpl: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import {{.authImport}} 4 | 5 | type Config struct { 6 | rest.RestConf 7 | {{.auth}} 8 | {{.jwtTrans}} 9 | } 10 | -------------------------------------------------------------------------------- /api/context.tpl: -------------------------------------------------------------------------------- 1 | package svc 2 | 3 | import ( 4 | {{.configImport}} 5 | ) 6 | 7 | type ServiceContext struct { 8 | Config {{.config}} 9 | {{.middleware}} 10 | } 11 | 12 | func NewServiceContext(c {{.config}}) *ServiceContext { 13 | return &ServiceContext{ 14 | Config: c, 15 | {{.middlewareAssignment}} 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /api/etc.tpl: -------------------------------------------------------------------------------- 1 | Name: {{.serviceName}} 2 | Host: {{.host}} 3 | Port: {{.port}} 4 | -------------------------------------------------------------------------------- /api/handler.tpl: -------------------------------------------------------------------------------- 1 | package {{.PkgName}} 2 | 3 | import ( 4 | vd "github.com/21888/go-tagexpr-new/validator" 5 | "ticket-server/common/xerr" 6 | "github.com/go-playground/validator/v10" 7 | "github.com/zeromicro/go-zero/rest/httpx" 8 | "net/http" 9 | 10 | "ticket-server/common/result" 11 | 12 | {{if .After1_1_10}}"github.com/zeromicro/go-zero/rest/httpx"{{end}} 13 | {{.ImportPackages}} 14 | ) 15 | 16 | func {{.HandlerName}}(svcCtx *svc.ServiceContext) http.HandlerFunc { 17 | return func(w http.ResponseWriter, r *http.Request) { 18 | {{if .HasRequest}}var req types.{{.RequestType}} 19 | if err := httpx.Parse(r, &req); err != nil { 20 | result.ParamErrorResult(r,w,err) 21 | return 22 | } 23 | if err := validator.New().StructCtx(r.Context(), req); err != nil { 24 | result.ParamErrorResult(r,w,err) 25 | return 26 | } 27 | if err := vd.Validate(req); err != nil { 28 | httpx.WriteJson(w, http.StatusBadRequest, result.Error(xerr.REUQEST_PARAM_ERROR, err.Error())) 29 | return 30 | } 31 | 32 | {{end}}l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx) 33 | {{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}&req{{end}}) 34 | result.HttpResult(r, w, {{if .HasResp}}resp{{else}}nil{{end}}, err) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /api/logic.tpl: -------------------------------------------------------------------------------- 1 | package {{.pkgName}} 2 | 3 | import ( 4 | {{.imports}} 5 | ) 6 | 7 | type {{.logic}} struct { 8 | logx.Logger 9 | ctx context.Context 10 | svcCtx *svc.ServiceContext 11 | } 12 | 13 | func New{{.logic}}(ctx context.Context, svcCtx *svc.ServiceContext) *{{.logic}} { 14 | return &{{.logic}}{ 15 | Logger: logx.WithContext(ctx), 16 | ctx: ctx, 17 | svcCtx: svcCtx, 18 | } 19 | } 20 | 21 | func (l *{{.logic}}) {{.function}}({{.request}}) {{.responseType}} { 22 | // add your logic here and delete this line 23 | 24 | {{.returnString}} 25 | } 26 | -------------------------------------------------------------------------------- /api/main.tpl: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | {{.importPackages}} 8 | {{/* "looklook/common/middleware"*/}} 9 | ) 10 | 11 | var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file") 12 | 13 | func main() { 14 | flag.Parse() 15 | 16 | var c config.Config 17 | conf.MustLoad(*configFile, &c) 18 | logx.DisableStat() 19 | 20 | ctx := svc.NewServiceContext(c) 21 | server := rest.MustNewServer(c.RestConf,rest.WithCors()) 22 | defer server.Stop() 23 | 24 | handler.RegisterHandlers(server, ctx) 25 | // 自定义错误 26 | httpx.SetErrorHandler(func(err error) (int, interface{}) { 27 | switch e := err.(type) { 28 | case *errorx.CodeError: 29 | return http.StatusOK, e.Data() 30 | default: 31 | return http.StatusInternalServerError, nil 32 | } 33 | }) 34 | fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) 35 | server.Start() 36 | } 37 | -------------------------------------------------------------------------------- /api/middleware.tpl: -------------------------------------------------------------------------------- 1 | 2 | package middleware 3 | 4 | import "net/http" 5 | 6 | type {{.name}} struct { 7 | } 8 | 9 | func New{{.name}}() *{{.name}} { 10 | return &{{.name}}{} 11 | } 12 | 13 | func (m *{{.name}})Handle(next http.HandlerFunc) http.HandlerFunc { 14 | return func(w http.ResponseWriter, r *http.Request) { 15 | // generate middleware implement function, delete after code implementation 16 | 17 | // Passthrough to next handler if need 18 | next(w, r) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /api/route-addition.tpl: -------------------------------------------------------------------------------- 1 | 2 | server.AddRoutes( 3 | {{.routes}} {{.jwt}}{{.signature}} {{.prefix}} {{.timeout}} 4 | ) 5 | -------------------------------------------------------------------------------- /api/routes.tpl: -------------------------------------------------------------------------------- 1 | // Code generated by goctl. DO NOT EDIT. 2 | package handler 3 | 4 | import ( 5 | "net/http"{{if .hasTimeout}} 6 | "time"{{end}} 7 | 8 | {{.importPackages}} 9 | ) 10 | 11 | func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { 12 | {{.routesAdditions}} 13 | } 14 | -------------------------------------------------------------------------------- /api/template.tpl: -------------------------------------------------------------------------------- 1 | 2 | syntax = "v1" 3 | 4 | info ( 5 | title: // TODO: add title 6 | desc: // TODO: add description 7 | author: "{{.gitUser}}" 8 | email: "{{.gitEmail}}" 9 | ) 10 | 11 | type request { 12 | // TODO: add members here and delete this comment 13 | } 14 | 15 | type response { 16 | // TODO: add members here and delete this comment 17 | } 18 | 19 | service {{.serviceName}} { 20 | @handler GetUser // TODO: set handler name and delete this comment 21 | get /users/id/:userId(request) returns(response) 22 | 23 | @handler CreateUser // TODO: set handler name and delete this comment 24 | post /users/create(request) 25 | } 26 | -------------------------------------------------------------------------------- /api/types.tpl: -------------------------------------------------------------------------------- 1 | // Code generated by goctl. DO NOT EDIT. 2 | package types{{if .containsTime}} 3 | import ( 4 | "time" 5 | ){{end}} 6 | {{.types}} 7 | -------------------------------------------------------------------------------- /docker/docker.tpl: -------------------------------------------------------------------------------- 1 | FROM golang:{{.Version}}alpine AS builder 2 | 3 | LABEL stage=gobuilder 4 | 5 | ENV CGO_ENABLED 0 6 | {{if .Chinese}}ENV GOPROXY https://goproxy.cn,direct 7 | {{end}}{{if .HasTimezone}} 8 | RUN apk update --no-cache && apk add --no-cache tzdata 9 | {{end}} 10 | WORKDIR /build 11 | 12 | ADD go.mod . 13 | ADD go.sum . 14 | RUN go mod download 15 | COPY . . 16 | {{if .Argument}}COPY {{.GoRelPath}}/etc /app/etc 17 | {{end}}RUN go build -ldflags="-s -w" -o /app/{{.ExeFile}} {{.GoRelPath}}/{{.GoFile}} 18 | 19 | 20 | FROM {{.BaseImage}} 21 | 22 | COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt 23 | {{if .HasTimezone}}COPY --from=builder /usr/share/zoneinfo/{{.Timezone}} /usr/share/zoneinfo/{{.Timezone}} 24 | ENV TZ {{.Timezone}} 25 | {{end}} 26 | WORKDIR /app 27 | COPY --from=builder /app/{{.ExeFile}} /app/{{.ExeFile}}{{if .Argument}} 28 | COPY --from=builder /app/etc /app/etc{{end}} 29 | {{if .HasPort}} 30 | EXPOSE {{.Port}} 31 | {{end}} 32 | CMD ["./{{.ExeFile}}"{{.Argument}}] 33 | -------------------------------------------------------------------------------- /goctl-v1.3.8-windows-amd64_2.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/21888/goctl-template/a4595aa98f1c5473d4aa7a8bcc747c5358e66cb5/goctl-v1.3.8-windows-amd64_2.zip -------------------------------------------------------------------------------- /goctl-v1.4.0-windows-amd64.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/21888/goctl-template/a4595aa98f1c5473d4aa7a8bcc747c5358e66cb5/goctl-v1.4.0-windows-amd64.zip -------------------------------------------------------------------------------- /kube/deployment.tpl: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: {{.Name}} 5 | namespace: {{.Namespace}} 6 | labels: 7 | app: {{.Name}} 8 | spec: 9 | replicas: {{.Replicas}} 10 | revisionHistoryLimit: {{.Revisions}} 11 | selector: 12 | matchLabels: 13 | app: {{.Name}} 14 | template: 15 | metadata: 16 | labels: 17 | app: {{.Name}} 18 | spec:{{if .ServiceAccount}} 19 | serviceAccountName: {{.ServiceAccount}}{{end}} 20 | containers: 21 | - name: {{.Name}} 22 | image: {{.Image}} 23 | lifecycle: 24 | preStop: 25 | exec: 26 | command: ["sh","-c","sleep 5"] 27 | ports: 28 | - containerPort: {{.Port}} 29 | readinessProbe: 30 | tcpSocket: 31 | port: {{.Port}} 32 | initialDelaySeconds: 5 33 | periodSeconds: 10 34 | livenessProbe: 35 | tcpSocket: 36 | port: {{.Port}} 37 | initialDelaySeconds: 15 38 | periodSeconds: 20 39 | resources: 40 | requests: 41 | cpu: {{.RequestCpu}}m 42 | memory: {{.RequestMem}}Mi 43 | limits: 44 | cpu: {{.LimitCpu}}m 45 | memory: {{.LimitMem}}Mi 46 | volumeMounts: 47 | - name: timezone 48 | mountPath: /etc/localtime 49 | {{if .Secret}}imagePullSecrets: 50 | - name: {{.Secret}} 51 | {{end}}volumes: 52 | - name: timezone 53 | hostPath: 54 | path: /usr/share/zoneinfo/Asia/Shanghai 55 | 56 | --- 57 | 58 | apiVersion: v1 59 | kind: Service 60 | metadata: 61 | name: {{.Name}}-svc 62 | namespace: {{.Namespace}} 63 | spec: 64 | ports: 65 | {{if .UseNodePort}}- nodePort: {{.NodePort}} 66 | port: {{.Port}} 67 | protocol: TCP 68 | targetPort: {{.Port}} 69 | type: NodePort{{else}}- port: {{.Port}}{{end}} 70 | selector: 71 | app: {{.Name}} 72 | 73 | --- 74 | 75 | apiVersion: autoscaling/v2beta1 76 | kind: HorizontalPodAutoscaler 77 | metadata: 78 | name: {{.Name}}-hpa-c 79 | namespace: {{.Namespace}} 80 | labels: 81 | app: {{.Name}}-hpa-c 82 | spec: 83 | scaleTargetRef: 84 | apiVersion: apps/v1 85 | kind: Deployment 86 | name: {{.Name}} 87 | minReplicas: {{.MinReplicas}} 88 | maxReplicas: {{.MaxReplicas}} 89 | metrics: 90 | - type: Resource 91 | resource: 92 | name: cpu 93 | targetAverageUtilization: 80 94 | 95 | --- 96 | 97 | apiVersion: autoscaling/v2beta1 98 | kind: HorizontalPodAutoscaler 99 | metadata: 100 | name: {{.Name}}-hpa-m 101 | namespace: {{.Namespace}} 102 | labels: 103 | app: {{.Name}}-hpa-m 104 | spec: 105 | scaleTargetRef: 106 | apiVersion: apps/v1 107 | kind: Deployment 108 | name: {{.Name}} 109 | minReplicas: {{.MinReplicas}} 110 | maxReplicas: {{.MaxReplicas}} 111 | metrics: 112 | - type: Resource 113 | resource: 114 | name: memory 115 | targetAverageUtilization: 80 116 | -------------------------------------------------------------------------------- /kube/job.tpl: -------------------------------------------------------------------------------- 1 | apiVersion: batch/v1 2 | kind: CronJob 3 | metadata: 4 | name: {{.Name}} 5 | namespace: {{.Namespace}} 6 | spec: 7 | successfulJobsHistoryLimit: {{.SuccessfulJobsHistoryLimit}} 8 | schedule: "{{.Schedule}}" 9 | jobTemplate: 10 | spec: 11 | template: 12 | spec:{{if .ServiceAccount}} 13 | serviceAccountName: {{.ServiceAccount}}{{end}} 14 | {{end}}containers: 15 | - name: {{.Name}} 16 | image: # todo image url 17 | resources: 18 | requests: 19 | cpu: {{.RequestCpu}}m 20 | memory: {{.RequestMem}}Mi 21 | limits: 22 | cpu: {{.LimitCpu}}m 23 | memory: {{.LimitMem}}Mi 24 | command: 25 | - ./{{.ServiceName}} 26 | - -f 27 | - ./{{.Name}}.yaml 28 | volumeMounts: 29 | - name: timezone 30 | mountPath: /etc/localtime 31 | imagePullSecrets: 32 | - name: # registry secret, if no, remove this 33 | restartPolicy: OnFailure 34 | volumes: 35 | - name: timezone 36 | hostPath: 37 | path: /usr/share/zoneinfo/Asia/Shanghai 38 | -------------------------------------------------------------------------------- /model/delete.tpl: -------------------------------------------------------------------------------- 1 | func (m *default{{.upperStartCamelObject}}Model) Delete(ctx context.Context, session sqlx.Session, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) error { 2 | {{if .withCache}}{{if .containsIndexCache}}_, err:=m.FindOne(ctx, {{.lowerStartCamelPrimaryKey}}) 3 | if err!=nil{ 4 | return err 5 | } 6 | 7 | {{end}} {{.keys}} 8 | _, err {{if .containsIndexCache}}={{else}}:={{end}} m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { 9 | query := fmt.Sprintf("delete from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table) 10 | if session!=nil{ 11 | return session.ExecCtx(ctx,query, {{.lowerStartCamelPrimaryKey}}) 12 | } 13 | return conn.ExecCtx(ctx, query, {{.lowerStartCamelPrimaryKey}}) 14 | }, {{.keyValues}}){{else}}query := fmt.Sprintf("delete from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table) 15 | if session!=nil{ 16 | _,err:= session.ExecCtx(ctx,query, {{.lowerStartCamelPrimaryKey}}) 17 | return err 18 | } 19 | _,err:=m.conn.ExecCtx(ctx, query, {{.lowerStartCamelPrimaryKey}}){{end}} 20 | return err 21 | } 22 | // DeleteAllTruncate 需要将data中除了ID外的唯一键设置为* 23 | func (m *default{{.upperStartCamelObject}}Model) DeleteAllTruncate(ctx context.Context, session sqlx.Session , data *{{.upperStartCamelObject}}) error { 24 | var id = "*" 25 | {{.keys}} 26 | 27 | _, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { 28 | query := fmt.Sprintf("truncate %s", m.table) 29 | if session != nil { 30 | return session.ExecCtx(ctx, query) 31 | } 32 | return conn.ExecCtx(ctx, query) 33 | }, {{.keyValues}}) 34 | return err 35 | } 36 | // DeleteBatchById 需要将data中除了ID外的唯一键设置为* 37 | func (m *default{{.upperStartCamelObject}}Model) DeleteBatchById(ctx context.Context, session sqlx.Session, data *{{.upperStartCamelObject}}, {{.lowerStartCamelPrimaryKey}}s []{{.dataType}}) error { 38 | var res []string 39 | for _, v := range {{.lowerStartCamelPrimaryKey}}s { 40 | res = append(res, fmt.Sprintf("'%v'", v)) 41 | } 42 | delArr := strings.Join(res, ",") 43 | var id = "*" 44 | {{.keys}} 45 | _, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { 46 | query := fmt.Sprintf("DELETE FROM %s WHERE {{.lowerStartCamelPrimaryKey}} in (%s)", m.table , delArr) 47 | if session != nil { 48 | return session.ExecCtx(ctx, query) 49 | } 50 | return conn.ExecCtx(ctx, query) 51 | }, {{.keyValues}}) 52 | return err 53 | } 54 | 55 | // DeleteBatchByIdAndSql 需要将data中除了ID外的唯一键设置为* 56 | func (m *default{{.upperStartCamelObject}}Model) DeleteBatchByIdAndSql(ctx context.Context, session sqlx.Session, data *{{.upperStartCamelObject}}, {{.lowerStartCamelPrimaryKey}}s []{{.dataType}}, andSql string) error { 57 | var res []string 58 | for _, v := range {{.lowerStartCamelPrimaryKey}}s { 59 | res = append(res, fmt.Sprintf("'%v'", v)) 60 | } 61 | delArr := strings.Join(res, ",") 62 | var id = "*" 63 | {{.keys}} 64 | _, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { 65 | query := fmt.Sprintf("DELETE FROM %s WHERE {{.lowerStartCamelPrimaryKey}} in (%s) %s", m.table , delArr, andSql) 66 | if session != nil { 67 | return session.ExecCtx(ctx, query) 68 | } 69 | return conn.ExecCtx(ctx, query) 70 | }, {{.keyValues}}) 71 | return err 72 | } 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | {{/* 84 | 85 | {{.keys}} 86 | appClientAppClientLogsIdKey := fmt.Sprintf("%s%v", cacheAppClientAppClientLogsIdPrefix, id) 87 | 88 | {{.keyValues}} 89 | appClientAppClientLogsIdKey 90 | 91 | {{.originalPrimaryKey}} 92 | `id` 93 | {{.lowerStartCamelPrimaryKey}} 94 | id 95 | {{.dataType}} 96 | int64 97 | {{.upperStartCamelObject}} 98 | AppClientLogs 数据库实体结构 99 | 100 | 101 | */}} 102 | 103 | {{/* 104 | 105 | map[ 106 | containsIndexCache:false 107 | data:{ 108 | { 109 | {app_client} 110 | {app_client} 111 | {{ {id} int64 1 1} true} 112 | map[] [0xc00010a500 0xc00010a550 0xc00010a5a0 0xc00010a5f0 0xc00010a640 0xc00010a690] 113 | } 114 | { 115 | cacheAppClientAppClientIdPrefix 116 | "cache:appClient:appClient:id:" 117 | cacheAppClientAppClientIdPrefix = "cache:appClient:appClient:id:" 118 | appClientAppClientIdKey 119 | fmt.Sprintf("%s%v", cacheAppClientAppClientIdPrefix, id) 120 | fmt.Sprintf("%s%v", cacheAppClientAppClientIdPrefix, data.Id) 121 | appClientAppClientIdKey := fmt.Sprintf("%s%v", cacheAppClientAppClientIdPrefix, id) 122 | appClientAppClientIdKey := fmt.Sprintf("%s%v", cacheAppClientAppClientIdPrefix, data.Id) 123 | [id] 124 | [0xc00049e7a0] 125 | } 126 | [] false 127 | } 128 | dataType:int64 129 | keyValues:appClientAppClientIdKey 130 | keys:appClientAppClientIdKey := fmt.Sprintf("%s%v", cacheAppClientAppClientIdPrefix, id) 131 | lowerStartCamelPrimaryKey:id 132 | originalPrimaryKey:`id` 133 | postgreSql:false 134 | upperStartCamelObject:AppClient 135 | withCache:true 136 | ] 137 | 138 | 139 | */}} -------------------------------------------------------------------------------- /model/err.tpl: -------------------------------------------------------------------------------- 1 | package {{.pkg}} 2 | 3 | import "github.com/zeromicro/go-zero/core/stores/sqlx" 4 | 5 | var ErrNotFound = sqlx.ErrNotFound 6 | -------------------------------------------------------------------------------- /model/field.tpl: -------------------------------------------------------------------------------- 1 | {{.name}} {{.type}} {{.tag}} {{if .hasComment}}// {{.comment}}{{end}} -------------------------------------------------------------------------------- /model/find-one-by-field-extra-method.tpl: -------------------------------------------------------------------------------- 1 | func (m *default{{.upperStartCamelObject}}Model) formatPrimary(primary interface{}) string { 2 | return fmt.Sprintf("%s%v", {{.primaryKeyLeft}}, primary) 3 | } 4 | func (m *default{{.upperStartCamelObject}}Model) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary interface{}) error { 5 | query := fmt.Sprintf("select %s from %s where {{.originalPrimaryField}} = {{if .postgreSql}}$1{{else}}?{{end}} limit 1", {{.lowerStartCamelObject}}Rows, m.table ) 6 | return conn.QueryRowCtx(ctx, v, query, primary) 7 | } 8 | -------------------------------------------------------------------------------- /model/find-one-by-field.tpl: -------------------------------------------------------------------------------- 1 | 2 | func (m *default{{.upperStartCamelObject}}Model) FindOneBy{{.upperField}}(ctx context.Context, {{.in}}) (*{{.upperStartCamelObject}}, error) { 3 | {{if .withCache}}{{.cacheKey}} 4 | var resp {{.upperStartCamelObject}} 5 | err := m.QueryRowIndexCtx(ctx, &resp, {{.cacheKeyVariable}}, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) (i interface{}, e error) { 6 | query := fmt.Sprintf("select %s from %s where {{.originalField}} limit 1", {{.lowerStartCamelObject}}Rows, m.table) 7 | if err := conn.QueryRowCtx(ctx, &resp, query, {{.lowerStartCamelField}}); err != nil { 8 | return nil, err 9 | } 10 | return resp.{{.upperStartCamelPrimaryKey}}, nil 11 | }, m.queryPrimary) 12 | switch err { 13 | case nil: 14 | return &resp, nil 15 | case sqlc.ErrNotFound: 16 | return nil, ErrNotFound 17 | default: 18 | return nil, err 19 | } 20 | }{{else}}var resp {{.upperStartCamelObject}} 21 | query := fmt.Sprintf("select %s from %s where {{.originalField}} limit 1", {{.lowerStartCamelObject}}Rows, m.table ) 22 | err := m.conn.QueryRowCtx(ctx, &resp, query, {{.lowerStartCamelField}}) 23 | switch err { 24 | case nil: 25 | return &resp, nil 26 | case sqlc.ErrNotFound: 27 | return nil, ErrNotFound 28 | default: 29 | return nil, err 30 | } 31 | }{{end}} 32 | 33 | -------------------------------------------------------------------------------- /model/find-one.tpl: -------------------------------------------------------------------------------- 1 | func (m *default{{.upperStartCamelObject}}Model) FindOne(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) (*{{.upperStartCamelObject}}, error) { 2 | {{if .withCache}}{{.cacheKey}} 3 | var resp {{.upperStartCamelObject}} 4 | err := m.QueryRowCtx(ctx, &resp, {{.cacheKeyVariable}}, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error { 5 | query := fmt.Sprintf("select %s from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}} limit 1", {{.lowerStartCamelObject}}Rows, m.table) 6 | return conn.QueryRowCtx(ctx, v, query, {{.lowerStartCamelPrimaryKey}}) 7 | }) 8 | switch err { 9 | case nil: 10 | return &resp, nil 11 | case sqlc.ErrNotFound: 12 | return nil, ErrNotFound 13 | default: 14 | return nil, err 15 | }{{else}}query := fmt.Sprintf("select %s from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}} limit 1", {{.lowerStartCamelObject}}Rows, m.table) 16 | var resp {{.upperStartCamelObject}} 17 | err := m.conn.QueryRowCtx(ctx, &resp, query, {{.lowerStartCamelPrimaryKey}}) 18 | switch err { 19 | case nil: 20 | return &resp, nil 21 | case sqlc.ErrNotFound: 22 | return nil, ErrNotFound 23 | default: 24 | return nil, err 25 | }{{end}} 26 | } 27 | -------------------------------------------------------------------------------- /model/import-no-cache.tpl: -------------------------------------------------------------------------------- 1 | import ( 2 | "context" 3 | "database/sql" 4 | "fmt" 5 | "strings" 6 | {{if .time}}"time"{{end}} 7 | 8 | "looklook/common/xerr" 9 | "looklook/common/globalkey" 10 | 11 | "github.com/zeromicro/go-zero/core/stores/builder" 12 | "github.com/zeromicro/go-zero/core/stores/sqlc" 13 | "github.com/zeromicro/go-zero/core/stores/sqlx" 14 | "github.com/zeromicro/go-zero/core/stringx" 15 | ) 16 | -------------------------------------------------------------------------------- /model/import.tpl: -------------------------------------------------------------------------------- 1 | import ( 2 | "context" 3 | "database/sql" 4 | "fmt" 5 | "strings" 6 | {{if .time}}"time"{{end}} 7 | 8 | {{/* "looklook/common/xerr"*/}} 9 | {{/* "looklook/common/globalkey"*/}} 10 | 11 | "github.com/zeromicro/go-zero/core/stores/builder" 12 | "github.com/zeromicro/go-zero/core/stores/cache" 13 | "github.com/zeromicro/go-zero/core/stores/sqlc" 14 | "github.com/zeromicro/go-zero/core/stores/sqlx" 15 | "github.com/zeromicro/go-zero/core/stringx" 16 | ) 17 | -------------------------------------------------------------------------------- /model/insert.tpl: -------------------------------------------------------------------------------- 1 | 2 | func (m *default{{.upperStartCamelObject}}Model) Insert(ctx context.Context,session sqlx.Session, data *{{.upperStartCamelObject}}) (sql.Result,error) { 3 | //data.DeleteTime = time.Unix(0,0) 4 | {{if .withCache}}{{.keys}} 5 | return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { 6 | query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet) 7 | if session != nil{ 8 | return session.ExecCtx(ctx,query,{{.expressionValues}}) 9 | } 10 | return conn.ExecCtx(ctx, query, {{.expressionValues}}) 11 | }, {{.keyValues}}){{else}} 12 | query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet) 13 | if session != nil{ 14 | return session.ExecCtx(ctx,query,{{.expressionValues}}) 15 | } 16 | return m.conn.ExecCtx(ctx, query, {{.expressionValues}}){{end}} 17 | } 18 | -------------------------------------------------------------------------------- /model/interface-delete.tpl: -------------------------------------------------------------------------------- 1 | Delete(ctx context.Context,session sqlx.Session, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) error 2 | DeleteAllTruncate(ctx context.Context, session sqlx.Session, data *{{.upperStartCamelObject}}) error 3 | DeleteBatchById(ctx context.Context, session sqlx.Session, data *{{.upperStartCamelObject}}, {{.lowerStartCamelPrimaryKey}}s []{{.dataType}}) error 4 | DeleteBatchByIdAndSql(ctx context.Context, session sqlx.Session, data *{{.upperStartCamelObject}}, {{.lowerStartCamelPrimaryKey}}s []{{.dataType}}, andSql string) error -------------------------------------------------------------------------------- /model/interface-find-one-by-field.tpl: -------------------------------------------------------------------------------- 1 | FindOneBy{{.upperField}}(ctx context.Context, {{.in}}) (*{{.upperStartCamelObject}}, error) -------------------------------------------------------------------------------- /model/interface-find-one.tpl: -------------------------------------------------------------------------------- 1 | FindOne(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) (*{{.upperStartCamelObject}}, error) -------------------------------------------------------------------------------- /model/interface-insert.tpl: -------------------------------------------------------------------------------- 1 | Insert(ctx context.Context, session sqlx.Session,data *{{.upperStartCamelObject}}) (sql.Result,error) -------------------------------------------------------------------------------- /model/interface-update.tpl: -------------------------------------------------------------------------------- 1 | Update(ctx context.Context,session sqlx.Session, data *{{.upperStartCamelObject}}) (sql.Result, error) 2 | UpdateAndSql(ctx context.Context,session sqlx.Session, data *{{.upperStartCamelObject}}, andSql string) (sql.Result, error) 3 | {{/*UpdateWithVersion(ctx context.Context,session sqlx.Session,data *{{.upperStartCamelObject}}) error*/}} -------------------------------------------------------------------------------- /model/model-gen.tpl: -------------------------------------------------------------------------------- 1 | // Code generated by goctl. DO NOT EDIT! 2 | 3 | package {{.pkg}} 4 | {{.imports}} 5 | {{.vars}} 6 | {{.types}} 7 | {{.new}} 8 | {{.insert}} 9 | {{.find}} 10 | {{.update}} 11 | {{.delete}} 12 | {{.extraMethod}} 13 | {{.tableName}} 14 | -------------------------------------------------------------------------------- /model/model-new.tpl: -------------------------------------------------------------------------------- 1 | 2 | func new{{.upperStartCamelObject}}Model(conn sqlx.SqlConn{{if .withCache}}, c cache.CacheConf{{end}}) *default{{.upperStartCamelObject}}Model { 3 | return &default{{.upperStartCamelObject}}Model{ 4 | {{if .withCache}}CachedConn: sqlc.NewConn(conn, c){{else}}conn:conn{{end}}, 5 | table: {{.table}}, 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /model/model.tpl: -------------------------------------------------------------------------------- 1 | package {{.pkg}} 2 | {{if .withCache}} 3 | import ( 4 | "context" 5 | {{/* "time"*/}} 6 | 7 | 8 | "github.com/zeromicro/go-zero/core/stores/cache" 9 | "github.com/zeromicro/go-zero/core/stores/sqlx" 10 | "github.com/Masterminds/squirrel" 11 | "github.com/pkg/errors" 12 | ) 13 | {{else}} 14 | import ( 15 | "context" 16 | {{/* "time"*/}} 17 | 18 | "github.com/zeromicro/go-zero/core/stores/sqlx" 19 | "github.com/Masterminds/squirrel" 20 | "github.com/pkg/errors" 21 | ) 22 | 23 | {{end}} 24 | var _ {{.upperStartCamelObject}}Model = (*custom{{.upperStartCamelObject}}Model)(nil) 25 | 26 | type ( 27 | // {{.upperStartCamelObject}}Model is an interface to be customized, add more methods here, 28 | // and implement the added methods in custom{{.upperStartCamelObject}}Model. 29 | {{.upperStartCamelObject}}Model interface { 30 | {{.lowerStartCamelObject}}Model 31 | Trans(ctx context.Context,fn func(context context.Context,session sqlx.Session) error) error 32 | RowBuilder() squirrel.SelectBuilder 33 | CountBuilder(field string) squirrel.SelectBuilder 34 | SumBuilder(field string) squirrel.SelectBuilder 35 | MaxBuilder(field string) squirrel.SelectBuilder 36 | MinBuilder(field string) squirrel.SelectBuilder 37 | {{/* 38 | DeleteSoft(ctx context.Context,session sqlx.Session, data *{{.upperStartCamelObject}}) error 39 | */}} 40 | FindOneByQuery(ctx context.Context,rowBuilder squirrel.SelectBuilder) (*{{.upperStartCamelObject}},error) 41 | FindSum(ctx context.Context,sumBuilder squirrel.SelectBuilder) (float64,error) 42 | FindCount(ctx context.Context,countBuilder squirrel.SelectBuilder) (int64,error) 43 | FindMaxInt64(ctx context.Context,sumBuilder squirrel.SelectBuilder) (int64,error) 44 | FindMinInt64(ctx context.Context,sumBuilder squirrel.SelectBuilder) (int64,error) 45 | FindAll(ctx context.Context,rowBuilder squirrel.SelectBuilder,orderBy string) ([]*{{.upperStartCamelObject}},error) 46 | FindPageListByPage(ctx context.Context,rowBuilder squirrel.SelectBuilder,page ,pageSize int64,orderBy string) ([]*{{.upperStartCamelObject}},error) 47 | FindPageListByIdDESC(ctx context.Context,rowBuilder squirrel.SelectBuilder ,preMinId ,pageSize int64) ([]*{{.upperStartCamelObject}},error) 48 | FindPageListByIdASC(ctx context.Context,rowBuilder squirrel.SelectBuilder,preMaxId ,pageSize int64) ([]*{{.upperStartCamelObject}},error) 49 | 50 | } 51 | 52 | custom{{.upperStartCamelObject}}Model struct { 53 | *default{{.upperStartCamelObject}}Model 54 | } 55 | ) 56 | 57 | // New{{.upperStartCamelObject}}Model returns a model for the database table. 58 | func New{{.upperStartCamelObject}}Model(conn sqlx.SqlConn{{if .withCache}}, c cache.CacheConf{{end}}) {{.upperStartCamelObject}}Model { 59 | return &custom{{.upperStartCamelObject}}Model{ 60 | default{{.upperStartCamelObject}}Model: new{{.upperStartCamelObject}}Model(conn{{if .withCache}}, c{{end}}), 61 | } 62 | } 63 | 64 | {{/* 65 | func (m *default{{.upperStartCamelObject}}Model) DeleteSoft(ctx context.Context,session sqlx.Session,data *{{.upperStartCamelObject}}) error { 66 | data.DelState = globalkey.DelStateYes 67 | data.DeleteTime = time.Now() 68 | if err:= m.UpdateWithVersion(ctx,session, data);err!= nil{ 69 | return errors.Wrapf(xerr.NewErrMsg("删除数据失败"),"{{.upperStartCamelObject}}Model delete err : %+v",err) 70 | } 71 | return nil 72 | } 73 | */}} 74 | 75 | func (m *default{{.upperStartCamelObject}}Model) FindOneByQuery(ctx context.Context,rowBuilder squirrel.SelectBuilder) (*{{.upperStartCamelObject}},error) { 76 | 77 | query, values, err := rowBuilder.ToSql() 78 | if err != nil { 79 | return nil, err 80 | } 81 | 82 | var resp {{.upperStartCamelObject}} 83 | {{if .withCache}}err = m.QueryRowNoCacheCtx(ctx,&resp, query, values...){{else}} 84 | err = m.conn.QueryRowCtx(ctx,&resp, query, values...) 85 | {{end}} 86 | switch err { 87 | case nil: 88 | return &resp, nil 89 | default: 90 | return nil, err 91 | } 92 | } 93 | 94 | 95 | func (m *default{{.upperStartCamelObject}}Model) FindSum(ctx context.Context,sumBuilder squirrel.SelectBuilder) (float64,error) { 96 | 97 | query, values, err := sumBuilder.ToSql() 98 | if err != nil { 99 | return 0, err 100 | } 101 | 102 | var resp float64 103 | {{if .withCache}}err = m.QueryRowNoCacheCtx(ctx,&resp, query, values...){{else}} 104 | err = m.conn.QueryRowCtx(ctx,&resp, query, values...) 105 | {{end}} 106 | switch err { 107 | case nil: 108 | return resp, nil 109 | default: 110 | return 0, err 111 | } 112 | } 113 | 114 | func (m *default{{.upperStartCamelObject}}Model) FindCount(ctx context.Context,countBuilder squirrel.SelectBuilder) (int64,error) { 115 | 116 | query, values, err := countBuilder.ToSql() 117 | if err != nil { 118 | return 0, err 119 | } 120 | 121 | var resp int64 122 | {{if .withCache}}err = m.QueryRowNoCacheCtx(ctx,&resp, query, values...){{else}} 123 | err = m.conn.QueryRowCtx(ctx,&resp, query, values...) 124 | {{end}} 125 | switch err { 126 | case nil: 127 | return resp, nil 128 | default: 129 | return 0, err 130 | } 131 | } 132 | 133 | 134 | func (m *default{{.upperStartCamelObject}}Model) FindMaxInt64(ctx context.Context,maxBuilder squirrel.SelectBuilder) (int64,error) { 135 | 136 | query, values, err := maxBuilder.ToSql() 137 | if err != nil { 138 | return 0, err 139 | } 140 | 141 | var resp int64 142 | {{if .withCache}}err = m.QueryRowNoCacheCtx(ctx,&resp, query, values...){{else}} 143 | err = m.conn.QueryRowCtx(ctx,&resp, query, values...) 144 | {{end}} 145 | switch err { 146 | case nil: 147 | return resp, nil 148 | default: 149 | return 0, err 150 | } 151 | } 152 | 153 | func (m *default{{.upperStartCamelObject}}Model) FindMinInt64(ctx context.Context,minBuilder squirrel.SelectBuilder) (int64,error) { 154 | 155 | query, values, err := minBuilder.ToSql() 156 | if err != nil { 157 | return 0, err 158 | } 159 | 160 | var resp int64 161 | {{if .withCache}}err = m.QueryRowNoCacheCtx(ctx,&resp, query, values...){{else}} 162 | err = m.conn.QueryRowCtx(ctx,&resp, query, values...) 163 | {{end}} 164 | switch err { 165 | case nil: 166 | return resp, nil 167 | default: 168 | return 0, err 169 | } 170 | } 171 | 172 | func (m *default{{.upperStartCamelObject}}Model) FindAll(ctx context.Context,rowBuilder squirrel.SelectBuilder,orderBy string) ([]*{{.upperStartCamelObject}},error) { 173 | 174 | if orderBy == ""{ 175 | rowBuilder = rowBuilder.OrderBy("id DESC") 176 | }else{ 177 | rowBuilder = rowBuilder.OrderBy(orderBy) 178 | } 179 | 180 | query, values, err := rowBuilder.ToSql() 181 | if err != nil { 182 | return nil, err 183 | } 184 | 185 | var resp []*{{.upperStartCamelObject}} 186 | {{if .withCache}}err = m.QueryRowsNoCacheCtx(ctx,&resp, query, values...){{else}} 187 | err = m.conn.QueryRowsCtx(ctx,&resp, query, values...) 188 | {{end}} 189 | switch err { 190 | case nil: 191 | return resp, nil 192 | default: 193 | return nil, err 194 | } 195 | } 196 | 197 | func (m *default{{.upperStartCamelObject}}Model) FindPageListByPage(ctx context.Context,rowBuilder squirrel.SelectBuilder,page ,pageSize int64,orderBy string) ([]*{{.upperStartCamelObject}},error) { 198 | 199 | if orderBy == ""{ 200 | rowBuilder = rowBuilder.OrderBy("id DESC") 201 | }else{ 202 | rowBuilder = rowBuilder.OrderBy(orderBy) 203 | } 204 | 205 | if page < 1{ 206 | page = 1 207 | } 208 | offset := (page - 1) * pageSize 209 | 210 | query, values, err := rowBuilder.Offset(uint64(offset)).Limit(uint64(pageSize)).ToSql() 211 | if err != nil { 212 | return nil, err 213 | } 214 | 215 | var resp []*{{.upperStartCamelObject}} 216 | {{if .withCache}}err = m.QueryRowsNoCacheCtx(ctx,&resp, query, values...){{else}} 217 | err = m.conn.QueryRowsCtx(ctx,&resp, query, values...) 218 | {{end}} 219 | switch err { 220 | case nil: 221 | return resp, nil 222 | default: 223 | return nil, err 224 | } 225 | } 226 | 227 | func (m *default{{.upperStartCamelObject}}Model) FindPageListByIdDESC(ctx context.Context,rowBuilder squirrel.SelectBuilder ,preMinId ,pageSize int64) ([]*{{.upperStartCamelObject}},error) { 228 | 229 | if preMinId > 0 { 230 | rowBuilder = rowBuilder.Where(" id < ? " , preMinId) 231 | } 232 | 233 | query, values, err := rowBuilder.OrderBy("id DESC").Limit(uint64(pageSize)).ToSql() 234 | if err != nil { 235 | return nil, err 236 | } 237 | 238 | var resp []*{{.upperStartCamelObject}} 239 | {{if .withCache}}err = m.QueryRowsNoCacheCtx(ctx,&resp, query, values...){{else}} 240 | err = m.conn.QueryRowsCtx(ctx,&resp, query, values...) 241 | {{end}} 242 | switch err { 243 | case nil: 244 | return resp, nil 245 | default: 246 | return nil, err 247 | } 248 | } 249 | 250 | //按照id升序分页查询数据,不支持排序 251 | func (m *default{{.upperStartCamelObject}}Model) FindPageListByIdASC(ctx context.Context,rowBuilder squirrel.SelectBuilder,preMaxId ,pageSize int64) ([]*{{.upperStartCamelObject}},error) { 252 | 253 | if preMaxId > 0 { 254 | rowBuilder = rowBuilder.Where(" id > ? " , preMaxId) 255 | } 256 | 257 | query, values, err := rowBuilder.OrderBy("id ASC").Limit(uint64(pageSize)).ToSql() 258 | if err != nil { 259 | return nil, err 260 | } 261 | 262 | var resp []*{{.upperStartCamelObject}} 263 | {{if .withCache}}err = m.QueryRowsNoCacheCtx(ctx,&resp, query, values...){{else}} 264 | err = m.conn.QueryRowsCtx(ctx,&resp, query, values...) 265 | {{end}} 266 | switch err { 267 | case nil: 268 | return resp, nil 269 | default: 270 | return nil, err 271 | } 272 | } 273 | 274 | // export logic 275 | func (m *default{{.upperStartCamelObject}}Model) Trans(ctx context.Context,fn func(ctx context.Context,session sqlx.Session) error) error { 276 | {{if .withCache}} 277 | return m.TransactCtx(ctx,func(ctx context.Context,session sqlx.Session) error { 278 | return fn(ctx,session) 279 | }) 280 | {{else}} 281 | return m.conn.TransactCtx(ctx,func(ctx context.Context,session sqlx.Session) error { 282 | return fn(ctx,session) 283 | }) 284 | {{end}} 285 | } 286 | 287 | // export logic 288 | func (m *default{{.upperStartCamelObject}}Model) RowBuilder() squirrel.SelectBuilder { 289 | return squirrel.Select({{.lowerStartCamelObject}}Rows).From(m.table) 290 | } 291 | 292 | // export logic 293 | func (m *default{{.upperStartCamelObject}}Model) CountBuilder(field string) squirrel.SelectBuilder { 294 | return squirrel.Select("COUNT("+field+")").From(m.table) 295 | } 296 | 297 | // export logic 298 | func (m *default{{.upperStartCamelObject}}Model) SumBuilder(field string) squirrel.SelectBuilder { 299 | return squirrel.Select("IFNULL(SUM("+field+"),0)").From(m.table) 300 | } 301 | 302 | // export logic 303 | func (m *default{{.upperStartCamelObject}}Model) MaxBuilder(field string) squirrel.SelectBuilder { 304 | return squirrel.Select("MAX("+field+")").From(m.table) 305 | } 306 | 307 | // export logic 308 | func (m *default{{.upperStartCamelObject}}Model) MinBuilder(field string) squirrel.SelectBuilder { 309 | return squirrel.Select("MIN("+field+")").From(m.table) 310 | } 311 | -------------------------------------------------------------------------------- /model/table-name.tpl: -------------------------------------------------------------------------------- 1 | 2 | func (m *default{{.upperStartCamelObject}}Model) tableName() string { 3 | return m.table 4 | } 5 | -------------------------------------------------------------------------------- /model/tag.tpl: -------------------------------------------------------------------------------- 1 | `db:"{{.field}}"` -------------------------------------------------------------------------------- /model/types.tpl: -------------------------------------------------------------------------------- 1 | 2 | type ( 3 | {{.lowerStartCamelObject}}Model interface{ 4 | {{.method}} 5 | } 6 | 7 | default{{.upperStartCamelObject}}Model struct { 8 | {{if .withCache}}sqlc.CachedConn{{else}}conn sqlx.SqlConn{{end}} 9 | table string 10 | } 11 | 12 | {{.upperStartCamelObject}} struct { 13 | {{.fields}} 14 | } 15 | ) 16 | -------------------------------------------------------------------------------- /model/update.tpl: -------------------------------------------------------------------------------- 1 | 2 | func (m *default{{.upperStartCamelObject}}Model) Update(ctx context.Context,session sqlx.Session, data *{{.upperStartCamelObject}}) (sql.Result,error) { 3 | {{if .withCache}}{{.keys}} 4 | return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { 5 | query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder) 6 | if session != nil{ 7 | return session.ExecCtx(ctx,query, {{.expressionValues}}) 8 | } 9 | return conn.ExecCtx(ctx, query, {{.expressionValues}}) 10 | }, {{.keyValues}}){{else}}query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder) 11 | if session != nil{ 12 | return session.ExecCtx(ctx,query, {{.expressionValues}}) 13 | } 14 | return m.conn.ExecCtx(ctx, query, {{.expressionValues}}){{end}} 15 | } 16 | 17 | 18 | 19 | 20 | func (m *default{{.upperStartCamelObject}}Model) UpdateAndSql(ctx context.Context,session sqlx.Session, data *{{.upperStartCamelObject}}, andSql string) (sql.Result,error) { 21 | {{if .withCache}}{{.keys}} 22 | return m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { 23 | query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}} %s", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder, andSql) 24 | if session != nil{ 25 | return session.ExecCtx(ctx,query, {{.expressionValues}}) 26 | } 27 | return conn.ExecCtx(ctx, query, {{.expressionValues}}) 28 | }, {{.keyValues}}){{else}}query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}} %s", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder, andSql) 29 | if session != nil{ 30 | return session.ExecCtx(ctx,query, {{.expressionValues}}) 31 | } 32 | return m.conn.ExecCtx(ctx, query, {{.expressionValues}}){{end}} 33 | } 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | {{/* 50 | func (m *default{{.upperStartCamelObject}}Model) UpdateWithVersion(ctx context.Context,session sqlx.Session,data *{{.upperStartCamelObject}}) error { 51 | 52 | oldVersion := data.Version 53 | data.Version += 1 54 | 55 | var sqlResult sql.Result 56 | var err error 57 | 58 | {{if .withCache}}{{.keys}} 59 | sqlResult,err = m.ExecCtx(ctx,func(ctx context.Context,conn sqlx.SqlConn) (result sql.Result, err error) { 60 | query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}} and version = ? ", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder) 61 | if session != nil{ 62 | return session.ExecCtx(ctx,query, {{.expressionValues}},oldVersion) 63 | } 64 | return conn.ExecCtx(ctx,query, {{.expressionValues}},oldVersion) 65 | }, {{.keyValues}}){{else}}query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}} and version = ? ", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder) 66 | if session != nil{ 67 | sqlResult,err = session.ExecCtx(ctx,query, {{.expressionValues}},oldVersion) 68 | }else{ 69 | sqlResult,err = m.conn.ExecCtx(ctx,query, {{.expressionValues}},oldVersion) 70 | } 71 | {{end}} 72 | if err != nil { 73 | return err 74 | } 75 | updateCount , err := sqlResult.RowsAffected() 76 | if err != nil{ 77 | return err 78 | } 79 | if updateCount == 0 { 80 | return xerr.NewErrCode(xerr.DB_UPDATE_AFFECTED_ZERO_ERROR) 81 | } 82 | 83 | return nil 84 | } 85 | */}} 86 | -------------------------------------------------------------------------------- /model/var.tpl: -------------------------------------------------------------------------------- 1 | 2 | var ( 3 | {{.lowerStartCamelObject}}FieldNames = builder.RawFieldNames(&{{.upperStartCamelObject}}{}{{if .postgreSql}},true{{end}}) 4 | {{.lowerStartCamelObject}}Rows = strings.Join({{.lowerStartCamelObject}}FieldNames, ",") 5 | {{.lowerStartCamelObject}}RowsExpectAutoSet = {{if .postgreSql}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, {{if .autoIncrement}}"{{.originalPrimaryKey}}",{{end}} "create_time", "update_time"), ","){{else}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, {{if .autoIncrement}}"{{.originalPrimaryKey}}",{{end}} "`create_time`", "`update_time`"), ","){{end}} 6 | {{.lowerStartCamelObject}}RowsWithPlaceHolder = {{if .postgreSql}}builder.PostgreSqlJoin(stringx.Remove({{.lowerStartCamelObject}}FieldNames, "{{.originalPrimaryKey}}", "create_time", "update_time")){{else}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, "{{.originalPrimaryKey}}", "`create_time`", "`update_time`"), "=?,") + "=?"{{end}} 7 | 8 | {{if .withCache}}{{.cacheKeys}}{{end}} 9 | ) 10 | -------------------------------------------------------------------------------- /mongo/err.tpl: -------------------------------------------------------------------------------- 1 | 2 | package model 3 | 4 | import "errors" 5 | 6 | var ErrNotFound = errors.New("not found") 7 | var ErrInvalidObjectId = errors.New("invalid objectId") 8 | -------------------------------------------------------------------------------- /mongo/model.tpl: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "context" 5 | 6 | "github.com/globalsign/mgo/bson" 7 | {{if .Cache}}cachec "github.com/zeromicro/go-zero/core/stores/cache" 8 | "github.com/zeromicro/go-zero/core/stores/mongoc"{{else}}"github.com/zeromicro/go-zero/core/stores/mongo"{{end}} 9 | ) 10 | 11 | {{if .Cache}}var prefix{{.Type}}CacheKey = "cache:{{.Type}}:"{{end}} 12 | 13 | type {{.Type}}Model interface{ 14 | Insert(ctx context.Context,data *{{.Type}}) error 15 | FindOne(ctx context.Context,id string) (*{{.Type}}, error) 16 | Update(ctx context.Context,data *{{.Type}}) error 17 | Delete(ctx context.Context,id string) error 18 | } 19 | 20 | type default{{.Type}}Model struct { 21 | {{if .Cache}}*mongoc.Model{{else}}*mongo.Model{{end}} 22 | } 23 | 24 | func New{{.Type}}Model(url, collection string{{if .Cache}}, c cachec.CacheConf{{end}}) {{.Type}}Model { 25 | return &default{{.Type}}Model{ 26 | Model: {{if .Cache}}mongoc.MustNewModel(url, collection, c){{else}}mongo.MustNewModel(url, collection){{end}}, 27 | } 28 | } 29 | 30 | 31 | func (m *default{{.Type}}Model) Insert(ctx context.Context, data *{{.Type}}) error { 32 | if !data.ID.Valid() { 33 | data.ID = bson.NewObjectId() 34 | } 35 | 36 | session, err := m.TakeSession() 37 | if err != nil { 38 | return err 39 | } 40 | 41 | defer m.PutSession(session) 42 | return m.GetCollection(session).Insert(data) 43 | } 44 | 45 | func (m *default{{.Type}}Model) FindOne(ctx context.Context, id string) (*{{.Type}}, error) { 46 | if !bson.IsObjectIdHex(id) { 47 | return nil, ErrInvalidObjectId 48 | } 49 | 50 | session, err := m.TakeSession() 51 | if err != nil { 52 | return nil, err 53 | } 54 | 55 | defer m.PutSession(session) 56 | var data {{.Type}} 57 | {{if .Cache}}key := prefix{{.Type}}CacheKey + id 58 | err = m.GetCollection(session).FindOneId(&data, key, bson.ObjectIdHex(id)) 59 | {{- else}} 60 | err = m.GetCollection(session).FindId(bson.ObjectIdHex(id)).One(&data) 61 | {{- end}} 62 | switch err { 63 | case nil: 64 | return &data,nil 65 | case {{if .Cache}}mongoc.ErrNotFound{{else}}mongo.ErrNotFound{{end}}: 66 | return nil,ErrNotFound 67 | default: 68 | return nil,err 69 | } 70 | } 71 | 72 | func (m *default{{.Type}}Model) Update(ctx context.Context, data *{{.Type}}) error { 73 | session, err := m.TakeSession() 74 | if err != nil { 75 | return err 76 | } 77 | 78 | defer m.PutSession(session) 79 | {{if .Cache}}key := prefix{{.Type}}CacheKey + data.ID.Hex() 80 | return m.GetCollection(session).UpdateId(data.ID, data, key) 81 | {{- else}} 82 | return m.GetCollection(session).UpdateId(data.ID, data) 83 | {{- end}} 84 | } 85 | 86 | func (m *default{{.Type}}Model) Delete(ctx context.Context, id string) error { 87 | session, err := m.TakeSession() 88 | if err != nil { 89 | return err 90 | } 91 | 92 | defer m.PutSession(session) 93 | {{if .Cache}}key := prefix{{.Type}}CacheKey + id 94 | return m.GetCollection(session).RemoveId(bson.ObjectIdHex(id), key) 95 | {{- else}} 96 | return m.GetCollection(session).RemoveId(bson.ObjectIdHex(id)) 97 | {{- end}} 98 | } 99 | -------------------------------------------------------------------------------- /newapi/newtemplate.tpl: -------------------------------------------------------------------------------- 1 | 2 | type Request { 3 | Name string `path:"name,options=you|me"` 4 | } 5 | 6 | type Response { 7 | Message string `json:"message"` 8 | } 9 | 10 | service {{.name}}-api { 11 | @handler {{.handler}}Handler 12 | get /from/:name(Request) returns (Response) 13 | } 14 | -------------------------------------------------------------------------------- /rpc/call-func.tpl: -------------------------------------------------------------------------------- 1 | 2 | {{if .hasComment}}{{.comment}}{{end}} 3 | func (m *default{{.serviceName}}) {{.method}}(ctx context.Context{{if .hasReq}}, in *{{.pbRequest}}{{end}}, opts ...grpc.CallOption) ({{if .notStream}}*{{.pbResponse}}, {{else}}{{.streamBody}},{{end}} error) { 4 | client := {{if .isCallPkgSameToGrpcPkg}}{{else}}{{.package}}.{{end}}New{{.rpcServiceName}}Client(m.cli.Conn()) 5 | return client.{{.method}}(ctx{{if .hasReq}}, in{{end}}, opts...) 6 | } 7 | -------------------------------------------------------------------------------- /rpc/call-interface-func.tpl: -------------------------------------------------------------------------------- 1 | {{if .hasComment}}{{.comment}} 2 | {{end}}{{.method}}(ctx context.Context{{if .hasReq}}, in *{{.pbRequest}}{{end}}, opts ...grpc.CallOption) ({{if .notStream}}*{{.pbResponse}}, {{else}}{{.streamBody}},{{end}} error) -------------------------------------------------------------------------------- /rpc/call.tpl: -------------------------------------------------------------------------------- 1 | {{.head}} 2 | 3 | package {{.filePackage}} 4 | 5 | import ( 6 | "context" 7 | 8 | {{.pbPackage}} 9 | {{if ne .pbPackage .protoGoPackage}}{{.protoGoPackage}}{{end}} 10 | 11 | "github.com/zeromicro/go-zero/zrpc" 12 | "google.golang.org/grpc" 13 | ) 14 | 15 | type ( 16 | {{.alias}} 17 | 18 | {{.serviceName}} interface { 19 | {{.interface}} 20 | } 21 | 22 | default{{.serviceName}} struct { 23 | cli zrpc.Client 24 | } 25 | ) 26 | 27 | func New{{.serviceName}}(cli zrpc.Client) {{.serviceName}} { 28 | return &default{{.serviceName}}{ 29 | cli: cli, 30 | } 31 | } 32 | 33 | {{.functions}} 34 | -------------------------------------------------------------------------------- /rpc/config.tpl: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "github.com/zeromicro/go-zero/core/stores/cache" 5 | "github.com/zeromicro/go-zero/zrpc" 6 | ) 7 | 8 | type Config struct { 9 | zrpc.RpcServerConf 10 | 11 | Mysql struct { 12 | DataSource string 13 | } 14 | Auth2 struct { 15 | AccessSecret string 16 | AccessExpire int64 17 | } 18 | 19 | CacheRedis cache.CacheConf 20 | 21 | Salt string 22 | } 23 | -------------------------------------------------------------------------------- /rpc/etc.tpl: -------------------------------------------------------------------------------- 1 | Name: {{.serviceName}}.rpc 2 | ListenOn: 127.0.0.1:8080 3 | Etcd: 4 | Hosts: 5 | - 127.0.0.1:2379 6 | Key: {{.serviceName}}.rpc 7 | -------------------------------------------------------------------------------- /rpc/logic-func.tpl: -------------------------------------------------------------------------------- 1 | {{if .hasComment}}{{.comment}}{{end}} 2 | func (l *{{.logicName}}) {{.method}} ({{if .hasReq}}in {{.request}}{{if .stream}},stream {{.streamBody}}{{end}}{{else}}stream {{.streamBody}}{{end}}) ({{if .hasReply}}{{.response}},{{end}} error) { 3 | // add your logic here and delete this line 4 | {{/*判断是否是添加函数*/}} 5 | {{if .isAddFunc}} 6 | // 示例代码 7 | /*entity := new(model.实体类名) 8 | _ = copier.Copy(&entity, in) 9 | if _, err := l.svcCtx.对应的model.Insert(l.ctx, nil, entity); err != nil { 10 | if errMySQL, ok := err.(*mysql.MySQLError); ok { 11 | switch errMySQL.Number { 12 | case 1062: 13 | return nil, xerr.NewErrCodeMsg(xerr.DB_ERROR, "主键冲突") 14 | } 15 | } 16 | return nil, err 17 | }*/ 18 | {{end}} 19 | {{/*判断是否是更新函数*/}} 20 | {{if .isUpdateFunc}} 21 | // 示例代码 22 | /*entity, err := l.svcCtx.对应的model.FindOne(l.ctx, in.Id) 23 | if err != nil { 24 | return nil, err 25 | } 26 | _ = copier.Copy(&entity, &in) 27 | // custom replacement entity field 28 | if _, err := l.svcCtx.对应的model.Update(l.ctx, nil, entity); err != nil { 29 | return nil, err 30 | }*/ 31 | {{end}} 32 | {{/*判断是否是删除函数*/}} 33 | {{if .isDelFunc}} 34 | // 示例代码 35 | /*if err := l.svcCtx.对应的model.DeleteBatchById(l.ctx, nil, in.Id); err != nil { 36 | return nil, err 37 | }*/ 38 | {{end}} 39 | {{/*判断是否是查询一条记录函数*/}} 40 | {{if .isGetOneFunc}} 41 | // 示例代码 42 | /*if one, err := l.svcCtx.对应的model.FindOne(l.ctx, in.Id); err != nil { 43 | if err == model.ErrNotFound { 44 | return nil, xerr.NewErrMsg(errorx.DataNotFound) 45 | } 46 | return nil, err 47 | } else { 48 | var res rpc包名.实体类名 49 | _ = copier.Copy(&res, one) 50 | return &{{.responseType}}{ 51 | res: &res, 52 | }, nil 53 | }*/ 54 | {{end}} 55 | {{/*判断是否是Search查询函数*/}} 56 | {{if .isSearchFunc}} 57 | // 示例代码 58 | /*if in.PageSize == enums.Zero { 59 | in.PageSize = enums.Ten 60 | } 61 | in.Page = in.Page + enums.One 62 | selectBuilder := l.svcCtx.对应的model.RowBuilder() 63 | countBuilder := l.svcCtx.对应的model.CountBuilder(model.ID_STR) 64 | // ============= 条件 ============= 65 | selectBuilder, countBuilder = l.selectJoinBuilder(in, selectBuilder, countBuilder) 66 | // ============= 查询 ============= 67 | if all, err := l.svcCtx.对应的model.FindPageListByPage(l.ctx, selectBuilder, in.Page, in.PageSize, "id DESC"); err != nil { 68 | return nil, err 69 | } else { 70 | var list []*rpc包名.实体类名 71 | for _, item := range all { 72 | var u rpc包名.实体类名 73 | if err := copier.Copy(&u, &item); err != nil { 74 | return nil, err 75 | } 76 | list = append(list, &u) 77 | } 78 | count, err := l.svcCtx.对应的model.FindCount(l.ctx, countBuilder) 79 | if err != nil { 80 | return nil, err 81 | } 82 | return &{{.responseType}}{ 83 | 实体类名: list, 84 | Total: count, 85 | }, nil 86 | }*/ 87 | {{end}} 88 | {{/*判断是否是Clear删除全部函数*/}} 89 | {{if .isClearFunc}} 90 | // 示例代码 91 | /*if err := l.svcCtx.对应的model.DeleteAllTruncate(l.ctx, nil); err != nil { 92 | return nil, err 93 | }*/ 94 | {{end}} 95 | {{/*判断是否是Count统计函数*/}} 96 | {{if .isCountFunc}} 97 | // 示例代码 98 | /*builder := l.svcCtx.对应的model.CountBuilder(model.ID_STR) 99 | count, err := l.svcCtx.对应的model.FindCount(l.ctx, builder) 100 | if err != nil { 101 | return nil, err 102 | } 103 | return &{{.responseType}}{ 104 | Count: count, 105 | }, nil*/ 106 | {{end}} 107 | {{/*判断是否是Set修改函数*/}} 108 | {{if .isSetFunc}} 109 | // 示例代码 110 | /* 111 | if findOne, err := l.svcCtx.对应的model.FindOne(l.ctx, in.Id); err != nil { 112 | return nil, err 113 | } else { 114 | findOne.字段 = in.字段 115 | if _, err := l.svcCtx.对应的model.Update(l.ctx, nil, findOne); err != nil { 116 | return nil, err 117 | } else { 118 | return &{{.responseType}}{}, nil 119 | } 120 | } 121 | */ 122 | {{end}} 123 | return {{if .hasReply}}&{{.responseType}}{},{{end}} nil 124 | } 125 | 126 | {{if .isSearchFunc}} 127 | /* 128 | func (l *{{.logicName}}) selectJoinBuilder(in {{.request}}, selectBuilder squirrel.SelectBuilder, countBuilder squirrel.SelectBuilder) (squirrel.SelectBuilder, squirrel.SelectBuilder) { 129 | 130 | //Model的实体结构 struct {} 131 | 132 | if in.Id != enums.Zero { 133 | pred := squirrel.Eq{ 134 | model.ID_STR: in.Id, 135 | } 136 | selectBuilder = selectBuilder.Where(pred) 137 | countBuilder = countBuilder.Where(pred) 138 | } 139 | if in.PId != model.SELECT_ALL { 140 | pred := squirrel.Eq{ 141 | "p_id": in.PId, 142 | } 143 | selectBuilder = selectBuilder.Where(pred) 144 | countBuilder = countBuilder.Where(pred) 145 | } 146 | if in.NoteName != model.EMPTY_STRING { 147 | pred := squirrel.Eq{ 148 | "note_name": in.NoteName, 149 | } 150 | selectBuilder = selectBuilder.Where(pred) 151 | countBuilder = countBuilder.Where(pred) 152 | } 153 | if in.CreatorTimeStart != model.SELECT_ALL { 154 | selectBuilder = selectBuilder.Where(squirrel.GtOrEq{ 155 | model.CREATOR_TIME_STR: in.CreatorTimeStart, 156 | }).Where(squirrel.LtOrEq{ 157 | model.CREATOR_TIME_STR: in.CreatorTimeEnd, 158 | }) 159 | countBuilder = countBuilder.Where(squirrel.GtOrEq{ 160 | model.CREATOR_TIME_STR: in.CreatorTimeStart, 161 | }).Where(squirrel.LtOrEq{ 162 | model.CREATOR_TIME_STR: in.CreatorTimeEnd, 163 | }) 164 | } 165 | 166 | return selectBuilder, countBuilder 167 | } 168 | */ 169 | {{end}} 170 | -------------------------------------------------------------------------------- /rpc/logic.tpl: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | {{.imports}} 7 | 8 | "github.com/zeromicro/go-zero/core/logx" 9 | ) 10 | 11 | type {{.logicName}} struct { 12 | ctx context.Context 13 | svcCtx *svc.ServiceContext 14 | logx.Logger 15 | } 16 | 17 | func New{{.logicName}}(ctx context.Context,svcCtx *svc.ServiceContext) *{{.logicName}} { 18 | return &{{.logicName}}{ 19 | ctx: ctx, 20 | svcCtx: svcCtx, 21 | Logger: logx.WithContext(ctx), 22 | } 23 | } 24 | {{.functions}} 25 | -------------------------------------------------------------------------------- /rpc/logic.tpl_1.3.8: -------------------------------------------------------------------------------- 1 | package logic 2 | 3 | import ( 4 | "context" 5 | 6 | {{.imports}} 7 | 8 | "github.com/zeromicro/go-zero/core/logx" 9 | ) 10 | 11 | type {{.logicName}} struct { 12 | ctx context.Context 13 | svcCtx *svc.ServiceContext 14 | logx.Logger 15 | } 16 | 17 | func New{{.logicName}}(ctx context.Context,svcCtx *svc.ServiceContext) *{{.logicName}} { 18 | return &{{.logicName}}{ 19 | ctx: ctx, 20 | svcCtx: svcCtx, 21 | Logger: logx.WithContext(ctx), 22 | } 23 | } 24 | {{.functions}} 25 | -------------------------------------------------------------------------------- /rpc/logic.tpl_1.4.0: -------------------------------------------------------------------------------- 1 | package {{.packageName}} 2 | 3 | import ( 4 | "context" 5 | 6 | {{.imports}} 7 | 8 | "github.com/zeromicro/go-zero/core/logx" 9 | ) 10 | 11 | type {{.logicName}} struct { 12 | ctx context.Context 13 | svcCtx *svc.ServiceContext 14 | logx.Logger 15 | } 16 | 17 | func New{{.logicName}}(ctx context.Context,svcCtx *svc.ServiceContext) *{{.logicName}} { 18 | return &{{.logicName}}{ 19 | ctx: ctx, 20 | svcCtx: svcCtx, 21 | Logger: logx.WithContext(ctx), 22 | } 23 | } 24 | {{.functions}} 25 | -------------------------------------------------------------------------------- /rpc/main.tpl: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | {{.imports}} 8 | 9 | "github.com/zeromicro/go-zero/core/conf" 10 | "github.com/zeromicro/go-zero/core/service" 11 | "github.com/zeromicro/go-zero/zrpc" 12 | "google.golang.org/grpc" 13 | "google.golang.org/grpc/reflection" 14 | ) 15 | 16 | var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file") 17 | 18 | func main() { 19 | flag.Parse() 20 | 21 | var c config.Config 22 | conf.MustLoad(*configFile, &c) 23 | ctx := svc.NewServiceContext(c) 24 | svr := server.New{{.serviceNew}}Server(ctx) 25 | 26 | s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { 27 | {{.pkg}}.Register{{.service}}Server(grpcServer, svr) 28 | 29 | if c.Mode == service.DevMode || c.Mode == service.TestMode { 30 | reflection.Register(grpcServer) 31 | } 32 | }) 33 | 34 | //rpc log 35 | s.AddUnaryInterceptors(rpcserver.LoggerInterceptor) 36 | 37 | defer s.Stop() 38 | 39 | fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) 40 | s.Start() 41 | } 42 | -------------------------------------------------------------------------------- /rpc/main.tpl_1.3.8: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | {{.imports}} 8 | "looklook/common/interceptor/rpcserver" 9 | 10 | "github.com/zeromicro/go-zero/core/conf" 11 | "github.com/zeromicro/go-zero/core/service" 12 | "github.com/zeromicro/go-zero/zrpc" 13 | "google.golang.org/grpc" 14 | "google.golang.org/grpc/reflection" 15 | ) 16 | 17 | var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file") 18 | 19 | func main() { 20 | flag.Parse() 21 | 22 | var c config.Config 23 | conf.MustLoad(*configFile, &c) 24 | ctx := svc.NewServiceContext(c) 25 | svr := server.New{{.serviceNew}}Server(ctx) 26 | 27 | s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { 28 | {{.pkg}}.Register{{.service}}Server(grpcServer, svr) 29 | 30 | if c.Mode == service.DevMode || c.Mode == service.TestMode { 31 | reflection.Register(grpcServer) 32 | } 33 | }) 34 | 35 | //rpc log 36 | s.AddUnaryInterceptors(rpcserver.LoggerInterceptor) 37 | 38 | defer s.Stop() 39 | 40 | fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) 41 | s.Start() 42 | } 43 | -------------------------------------------------------------------------------- /rpc/main.tpl_1.4.0: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | {{.imports}} 8 | 9 | "github.com/zeromicro/go-zero/core/conf" 10 | "github.com/zeromicro/go-zero/core/service" 11 | "github.com/zeromicro/go-zero/zrpc" 12 | "google.golang.org/grpc" 13 | "google.golang.org/grpc/reflection" 14 | ) 15 | 16 | var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file") 17 | 18 | func main() { 19 | flag.Parse() 20 | 21 | var c config.Config 22 | conf.MustLoad(*configFile, &c) 23 | ctx := svc.NewServiceContext(c) 24 | 25 | s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { 26 | {{range .serviceNames}} {{.Pkg}}.Register{{.Service}}Server(grpcServer, {{.ServerPkg}}.New{{.Service}}Server(ctx)) 27 | {{end}} 28 | if c.Mode == service.DevMode || c.Mode == service.TestMode { 29 | reflection.Register(grpcServer) 30 | } 31 | }) 32 | 33 | //rpc log 34 | s.AddUnaryInterceptors(rpcserver.LoggerInterceptor) 35 | 36 | defer s.Stop() 37 | 38 | fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) 39 | s.Start() 40 | } 41 | -------------------------------------------------------------------------------- /rpc/server-func.tpl: -------------------------------------------------------------------------------- 1 | {{/*1.3.8*/}} 2 | {{if .hasComment}}{{.comment}}{{end}} 3 | func (s *{{.server}}Server) {{.method}} ({{if .notStream}}ctx context.Context,{{if .hasReq}} in {{.request}}{{end}}{{else}}{{if .hasReq}} in {{.request}},{{end}}stream {{.streamBody}}{{end}}) ({{if .notStream}}{{.response}},{{end}}error) { 4 | l := logic.New{{.logicName}}({{if .notStream}}ctx,{{else}}stream.Context(),{{end}}s.svcCtx) 5 | return l.{{.method}}({{if .hasReq}}in{{if .stream}} ,stream{{end}}{{else}}{{if .stream}}stream{{end}}{{end}}) 6 | } 7 | 8 | 9 | {{/*1.4.0*/}} 10 | {{/* 11 | {{if .hasComment}}{{.comment}}{{end}} 12 | func (s *{{.server}}Server) {{.method}} ({{if .notStream}}ctx context.Context,{{if .hasReq}} in {{.request}}{{end}}{{else}}{{if .hasReq}} in {{.request}},{{end}}stream {{.streamBody}}{{end}}) ({{if .notStream}}{{.response}},{{end}}error) { 13 | l := {{.logicPkg}}.New{{.logicName}}({{if .notStream}}ctx,{{else}}stream.Context(),{{end}}s.svcCtx) 14 | return l.{{.method}}({{if .hasReq}}in{{if .stream}} ,stream{{end}}{{else}}{{if .stream}}stream{{end}}{{end}}) 15 | } 16 | */}} 17 | -------------------------------------------------------------------------------- /rpc/server-func.tpl_1.3.8: -------------------------------------------------------------------------------- 1 | 2 | {{if .hasComment}}{{.comment}}{{end}} 3 | func (s *{{.server}}Server) {{.method}} ({{if .notStream}}ctx context.Context,{{if .hasReq}} in {{.request}}{{end}}{{else}}{{if .hasReq}} in {{.request}},{{end}}stream {{.streamBody}}{{end}}) ({{if .notStream}}{{.response}},{{end}}error) { 4 | l := logic.New{{.logicName}}({{if .notStream}}ctx,{{else}}stream.Context(),{{end}}s.svcCtx) 5 | return l.{{.method}}({{if .hasReq}}in{{if .stream}} ,stream{{end}}{{else}}{{if .stream}}stream{{end}}{{end}}) 6 | } 7 | -------------------------------------------------------------------------------- /rpc/server-func.tpl_1.4.0: -------------------------------------------------------------------------------- 1 | {{/* 2 | // 1.3.8 3 | {{if .hasComment}}{{.comment}}{{end}} 4 | func (s *{{.server}}Server) {{.method}} ({{if .notStream}}ctx context.Context,{{if .hasReq}} in {{.request}}{{end}}{{else}}{{if .hasReq}} in {{.request}},{{end}}stream {{.streamBody}}{{end}}) ({{if .notStream}}{{.response}},{{end}}error) { 5 | l := logic.New{{.logicName}}({{if .notStream}}ctx,{{else}}stream.Context(),{{end}}s.svcCtx) 6 | return l.{{.method}}({{if .hasReq}}in{{if .stream}} ,stream{{end}}{{else}}{{if .stream}}stream{{end}}{{end}}) 7 | } 8 | */}} 9 | 10 | {{/*1.4.0*/}} 11 | {{if .hasComment}}{{.comment}}{{end}} 12 | func (s *{{.server}}Server) {{.method}} ({{if .notStream}}ctx context.Context,{{if .hasReq}} in {{.request}}{{end}}{{else}}{{if .hasReq}} in {{.request}},{{end}}stream {{.streamBody}}{{end}}) ({{if .notStream}}{{.response}},{{end}}error) { 13 | l := {{.logicPkg}}.New{{.logicName}}({{if .notStream}}ctx,{{else}}stream.Context(),{{end}}s.svcCtx) 14 | return l.{{.method}}({{if .hasReq}}in{{if .stream}} ,stream{{end}}{{else}}{{if .stream}}stream{{end}}{{end}}) 15 | } 16 | -------------------------------------------------------------------------------- /rpc/server.tpl: -------------------------------------------------------------------------------- 1 | {{.head}} 2 | 3 | package server 4 | 5 | import ( 6 | {{if .notStream}}"context"{{end}} 7 | 8 | {{.imports}} 9 | ) 10 | 11 | type {{.server}}Server struct { 12 | svcCtx *svc.ServiceContext 13 | {{.unimplementedServer}} 14 | } 15 | 16 | func New{{.server}}Server(svcCtx *svc.ServiceContext) *{{.server}}Server { 17 | return &{{.server}}Server{ 18 | svcCtx: svcCtx, 19 | } 20 | } 21 | 22 | {{.funcs}} 23 | -------------------------------------------------------------------------------- /rpc/svc.tpl: -------------------------------------------------------------------------------- 1 | package svc 2 | 3 | import {{.imports}} 4 | 5 | type ServiceContext struct { 6 | Config config.Config 7 | } 8 | 9 | func NewServiceContext(c config.Config) *ServiceContext { 10 | return &ServiceContext{ 11 | Config:c, 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /rpc/template.tpl: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package {{.package}}; 4 | option go_package="./{{.package}}"; 5 | 6 | message Request { 7 | string ping = 1; 8 | } 9 | 10 | message Response { 11 | string pong = 1; 12 | } 13 | 14 | service {{.serviceName}} { 15 | rpc Ping(Request) returns(Response); 16 | } 17 | --------------------------------------------------------------------------------