diff --git a/README.md b/README.md index eee63e12..a96ea471 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,8 @@ #### 使用说明 -1. goctl api go -api home-user-auth.api -dir home-user-auth -2. goctl model mysql ddl --src ./ddl/fs_canteen_type.sql --dir model/ +1. sh fs_gen_api.sh home-user-auth # 序列化api +2. sh fs_gen_mysql_model.sh fs_canteen_type # 根据ddl序列化mysql model 3. xxxx #### 参与贡献 diff --git a/fs_gen_api.sh b/fs_gen_api.sh new file mode 100755 index 00000000..56320f79 --- /dev/null +++ b/fs_gen_api.sh @@ -0,0 +1,2 @@ +#! /bin/bash +goctl api go -api server_api/$1.api -dir $1 --home ./goctl_template/ \ No newline at end of file diff --git a/fs_gen_mysql_model.sh b/fs_gen_mysql_model.sh new file mode 100755 index 00000000..95bf5fbd --- /dev/null +++ b/fs_gen_mysql_model.sh @@ -0,0 +1,2 @@ +#! /bin/bash +goctl model mysql ddl --src ./ddl/$1.sql --dir model/ --home ./goctl_template \ No newline at end of file diff --git a/goctl_template/api/config.tpl b/goctl_template/api/config.tpl new file mode 100644 index 00000000..55127efb --- /dev/null +++ b/goctl_template/api/config.tpl @@ -0,0 +1,9 @@ +package config + +import {{.authImport}} + +type Config struct { + rest.RestConf + {{.auth}} + {{.jwtTrans}} +} diff --git a/goctl_template/api/context.tpl b/goctl_template/api/context.tpl new file mode 100644 index 00000000..99773904 --- /dev/null +++ b/goctl_template/api/context.tpl @@ -0,0 +1,20 @@ +package svc + +import ( + {{.configImport}} + "github.com/zeromicro/go-zero/core/stores/sqlx" +) + +type ServiceContext struct { + Config {{.config}} + {{.middleware}} + MysqlConn sqlx.SqlConn +} + +func NewServiceContext(c {{.config}}) *ServiceContext { + return &ServiceContext{ + Config: c, + MysqlConn: sqlx.NewMysql(c.SourceMysql), + {{.middlewareAssignment}} + } +} diff --git a/goctl_template/api/etc.tpl b/goctl_template/api/etc.tpl new file mode 100644 index 00000000..cf7aee4b --- /dev/null +++ b/goctl_template/api/etc.tpl @@ -0,0 +1,4 @@ +Name: {{.serviceName}} +Host: {{.host}} +Port: {{.port}} +SourceMysql: "" diff --git a/goctl_template/api/handler.tpl b/goctl_template/api/handler.tpl new file mode 100644 index 00000000..336b8eac --- /dev/null +++ b/goctl_template/api/handler.tpl @@ -0,0 +1,35 @@ +package {{.PkgName}} + +import ( + "net/http" + "errors" + + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + + {{.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.OkJsonCtx(r.Context(), w, &types.Response{ + Code: 510, + Message: "parameter error", + }) + logx.Info(err) + return + } + + {{end}}l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx) + {{if .HasResp}}resp{{end}} := l.{{.Call}}({{if .HasRequest}}&req{{end}}) + if resp != nil { + {{if .HasResp}}httpx.OkJsonCtx(r.Context(), w, resp){{else}}httpx.Ok(w){{end}} + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) + } + } +} diff --git a/goctl_template/api/logic.tpl b/goctl_template/api/logic.tpl new file mode 100644 index 00000000..9311f85d --- /dev/null +++ b/goctl_template/api/logic.tpl @@ -0,0 +1,26 @@ +package {{.pkgName}} + +import ( + {{.imports}} +) + +type {{.logic}} struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func New{{.logic}}(ctx context.Context, svcCtx *svc.ServiceContext) *{{.logic}} { + return &{{.logic}}{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *{{.logic}}) {{.function}}({{.request}}) (resp *types.Response) { + // 必须返回response, 前端需要的是内部约定的Code码, 处理相关的逻辑. 例子(eg): resp.Set(501, "error") + resp = &types.Response{} + + {{.returnString}} resp +} diff --git a/goctl_template/api/main.tpl b/goctl_template/api/main.tpl new file mode 100644 index 00000000..ad1a46d0 --- /dev/null +++ b/goctl_template/api/main.tpl @@ -0,0 +1,26 @@ +package main + +import ( + "flag" + "fmt" + + {{.importPackages}} +) + +var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + + server := rest.MustNewServer(c.RestConf) + defer server.Stop() + + ctx := svc.NewServiceContext(c) + handler.RegisterHandlers(server, ctx) + + fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port) + server.Start() +} diff --git a/goctl_template/api/middleware.tpl b/goctl_template/api/middleware.tpl new file mode 100644 index 00000000..3a9f8e91 --- /dev/null +++ b/goctl_template/api/middleware.tpl @@ -0,0 +1,19 @@ +package middleware + +import "net/http" + +type {{.name}} struct { +} + +func New{{.name}}() *{{.name}} { + return &{{.name}}{} +} + +func (m *{{.name}})Handle(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + // TODO generate middleware implement function, delete after code implementation + + // Passthrough to next handler if need + next(w, r) + } +} diff --git a/goctl_template/api/route-addition.tpl b/goctl_template/api/route-addition.tpl new file mode 100644 index 00000000..bb8a5dfe --- /dev/null +++ b/goctl_template/api/route-addition.tpl @@ -0,0 +1,4 @@ + + server.AddRoutes( + {{.routes}} {{.jwt}}{{.signature}} {{.prefix}} {{.timeout}} {{.maxBytes}} + ) diff --git a/goctl_template/api/routes.tpl b/goctl_template/api/routes.tpl new file mode 100644 index 00000000..f13fb111 --- /dev/null +++ b/goctl_template/api/routes.tpl @@ -0,0 +1,13 @@ +// Code generated by goctl. DO NOT EDIT. +package handler + +import ( + "net/http"{{if .hasTimeout}} + "time"{{end}} + + {{.importPackages}} +) + +func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { + {{.routesAdditions}} +} diff --git a/goctl_template/api/template.tpl b/goctl_template/api/template.tpl new file mode 100644 index 00000000..2176441c --- /dev/null +++ b/goctl_template/api/template.tpl @@ -0,0 +1,24 @@ +syntax = "v1" + +info ( + title: // TODO: add title + desc: // TODO: add description + author: "{{.gitUser}}" + email: "{{.gitEmail}}" +) + +type request { + // TODO: add members here and delete this comment +} + +type response { + // TODO: add members here and delete this comment +} + +service {{.serviceName}} { + @handler GetUser // TODO: set handler name and delete this comment + get /users/id/:userId(request) returns(response) + + @handler CreateUser // TODO: set handler name and delete this comment + post /users/create(request) +} diff --git a/goctl_template/api/types.tpl b/goctl_template/api/types.tpl new file mode 100644 index 00000000..0875ec47 --- /dev/null +++ b/goctl_template/api/types.tpl @@ -0,0 +1,55 @@ +// Code generated by goctl. DO NOT EDIT. +package types +import ( + {{if .containsTime}}"time"{{end}} + + "fusenapi/utils/basic" +) +{{.types}} + +// Set 设置Response的Code和Message值 +func (resp *Response) Set(Code int, Message string) { + resp.Code = Code + resp.Message = Message +} + +// Set 设置整个Response +func (resp *Response) SetWithData(Code int, Message string, Data interface{}) { + resp.Code = Code + resp.Message = Message + resp.Data = Data +} + +// SetMessage 设置Response的Message +func (resp *Response) SetMessage(msg string) { + resp.Message = msg +} + +// SetWithData 设置Data +func (resp *Response) SetData(Data interface{}) { + resp.Data = Data +} + +// SetWithData 设置Response的Code和Message值 带Data入参数 +func (resp *Response) SetCode(Code int) { + resp.Code = Code +} + + +// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) { + resp.Code = sr.Code + resp.Message = sr.Message + if len(data) == 1 { + resp.Data = data[0] + } +} + +// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) { + resp.Code = sr.Code + resp.Message = msg + if len(data) == 1 { + resp.Data = data[0] + } +} \ No newline at end of file diff --git a/goctl_template/docker/docker.tpl b/goctl_template/docker/docker.tpl new file mode 100644 index 00000000..d1b5ff44 --- /dev/null +++ b/goctl_template/docker/docker.tpl @@ -0,0 +1,33 @@ +FROM golang:{{.Version}}alpine AS builder + +LABEL stage=gobuilder + +ENV CGO_ENABLED 0 +{{if .Chinese}}ENV GOPROXY https://goproxy.cn,direct +RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories +{{end}}{{if .HasTimezone}} +RUN apk update --no-cache && apk add --no-cache tzdata +{{end}} +WORKDIR /build + +ADD go.mod . +ADD go.sum . +RUN go mod download +COPY . . +{{if .Argument}}COPY {{.GoRelPath}}/etc /app/etc +{{end}}RUN go build -ldflags="-s -w" -o /app/{{.ExeFile}} {{.GoMainFrom}} + + +FROM {{.BaseImage}} + +COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt +{{if .HasTimezone}}COPY --from=builder /usr/share/zoneinfo/{{.Timezone}} /usr/share/zoneinfo/{{.Timezone}} +ENV TZ {{.Timezone}} +{{end}} +WORKDIR /app +COPY --from=builder /app/{{.ExeFile}} /app/{{.ExeFile}}{{if .Argument}} +COPY --from=builder /app/etc /app/etc{{end}} +{{if .HasPort}} +EXPOSE {{.Port}} +{{end}} +CMD ["./{{.ExeFile}}"{{.Argument}}] diff --git a/goctl_template/gateway/etc.tpl b/goctl_template/gateway/etc.tpl new file mode 100644 index 00000000..0a70f1ac --- /dev/null +++ b/goctl_template/gateway/etc.tpl @@ -0,0 +1,18 @@ +Name: gateway-example # gateway name +Host: localhost # gateway host +Port: 8888 # gateway port +Upstreams: # upstreams + - Grpc: # grpc upstream + Target: 0.0.0.0:8080 # grpc target,the direct grpc server address,for only one node +# Endpoints: [0.0.0.0:8080,192.168.120.1:8080] # grpc endpoints, the grpc server address list, for multiple nodes +# Etcd: # etcd config, if you want to use etcd to discover the grpc server address +# Hosts: [127.0.0.1:2378,127.0.0.1:2379] # etcd hosts +# Key: greet.grpc # the discovery key + # protoset mode + ProtoSets: + - hello.pb + # Mappings can also be written in proto options +# Mappings: # routes mapping +# - Method: get +# Path: /ping +# RpcPath: hello.Hello/Ping diff --git a/goctl_template/gateway/main.tpl b/goctl_template/gateway/main.tpl new file mode 100644 index 00000000..62734516 --- /dev/null +++ b/goctl_template/gateway/main.tpl @@ -0,0 +1,20 @@ +package main + +import ( + "flag" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/gateway" +) + +var configFile = flag.String("f", "etc/gateway.yaml", "config file") + +func main() { + flag.Parse() + + var c gateway.GatewayConf + conf.MustLoad(*configFile, &c) + gw := gateway.MustNewServer(c) + defer gw.Stop() + gw.Start() +} diff --git a/goctl_template/kube/deployment.tpl b/goctl_template/kube/deployment.tpl new file mode 100644 index 00000000..14145df2 --- /dev/null +++ b/goctl_template/kube/deployment.tpl @@ -0,0 +1,117 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{.Name}} + namespace: {{.Namespace}} + labels: + app: {{.Name}} +spec: + replicas: {{.Replicas}} + revisionHistoryLimit: {{.Revisions}} + selector: + matchLabels: + app: {{.Name}} + template: + metadata: + labels: + app: {{.Name}} + spec:{{if .ServiceAccount}} + serviceAccountName: {{.ServiceAccount}}{{end}} + containers: + - name: {{.Name}} + image: {{.Image}} + {{if .ImagePullPolicy}}imagePullPolicy: {{.ImagePullPolicy}} + {{end}}ports: + - containerPort: {{.Port}} + readinessProbe: + tcpSocket: + port: {{.Port}} + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + tcpSocket: + port: {{.Port}} + initialDelaySeconds: 15 + periodSeconds: 20 + resources: + requests: + cpu: {{.RequestCpu}}m + memory: {{.RequestMem}}Mi + limits: + cpu: {{.LimitCpu}}m + memory: {{.LimitMem}}Mi + volumeMounts: + - name: timezone + mountPath: /etc/localtime + {{if .Secret}}imagePullSecrets: + - name: {{.Secret}} + {{end}}volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai + +--- + +apiVersion: v1 +kind: Service +metadata: + name: {{.Name}}-svc + namespace: {{.Namespace}} +spec: + ports: + {{if .UseNodePort}}- nodePort: {{.NodePort}} + port: {{.Port}} + protocol: TCP + targetPort: {{.TargetPort}} + type: NodePort{{else}}- port: {{.Port}} + targetPort: {{.TargetPort}}{{end}} + selector: + app: {{.Name}} + +--- + +apiVersion: autoscaling/v2beta2 +kind: HorizontalPodAutoscaler +metadata: + name: {{.Name}}-hpa-c + namespace: {{.Namespace}} + labels: + app: {{.Name}}-hpa-c +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: {{.Name}} + minReplicas: {{.MinReplicas}} + maxReplicas: {{.MaxReplicas}} + metrics: + - type: Resource + resource: + name: cpu + target: + type: Utilization + averageUtilization: 80 + +--- + +apiVersion: autoscaling/v2beta2 +kind: HorizontalPodAutoscaler +metadata: + name: {{.Name}}-hpa-m + namespace: {{.Namespace}} + labels: + app: {{.Name}}-hpa-m +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: {{.Name}} + minReplicas: {{.MinReplicas}} + maxReplicas: {{.MaxReplicas}} + metrics: + - type: Resource + resource: + name: memory + target: + type: Utilization + averageUtilization: 80 diff --git a/goctl_template/kube/job.tpl b/goctl_template/kube/job.tpl new file mode 100644 index 00000000..0da72ede --- /dev/null +++ b/goctl_template/kube/job.tpl @@ -0,0 +1,37 @@ +apiVersion: batch/v1 +kind: CronJob +metadata: + name: {{.Name}} + namespace: {{.Namespace}} +spec: + successfulJobsHistoryLimit: {{.SuccessfulJobsHistoryLimit}} + schedule: "{{.Schedule}}" + jobTemplate: + spec: + template: + spec:{{if .ServiceAccount}} + serviceAccountName: {{.ServiceAccount}}{{end}} + {{end}}containers: + - name: {{.Name}} + image: # todo image url + resources: + requests: + cpu: {{.RequestCpu}}m + memory: {{.RequestMem}}Mi + limits: + cpu: {{.LimitCpu}}m + memory: {{.LimitMem}}Mi + command: + - ./{{.ServiceName}} + - -f + - ./{{.Name}}.yaml + volumeMounts: + - name: timezone + mountPath: /etc/localtime + imagePullSecrets: + - name: # registry secret, if no, remove this + restartPolicy: OnFailure + volumes: + - name: timezone + hostPath: + path: /usr/share/zoneinfo/Asia/Shanghai diff --git a/goctl_template/model/delete.tpl b/goctl_template/model/delete.tpl new file mode 100644 index 00000000..fb995c26 --- /dev/null +++ b/goctl_template/model/delete.tpl @@ -0,0 +1,14 @@ +func (m *default{{.upperStartCamelObject}}Model) Delete(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) error { + {{if .withCache}}{{if .containsIndexCache}}data, err:=m.FindOne(ctx, {{.lowerStartCamelPrimaryKey}}) + if err!=nil{ + return err + } + +{{end}} {{.keys}} + _, err {{if .containsIndexCache}}={{else}}:={{end}} m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("delete from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table) + return conn.ExecCtx(ctx, query, {{.lowerStartCamelPrimaryKey}}) + }, {{.keyValues}}){{else}}query := fmt.Sprintf("delete from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table) + _,err:=m.conn.ExecCtx(ctx, query, {{.lowerStartCamelPrimaryKey}}){{end}} + return err +} diff --git a/goctl_template/model/err.tpl b/goctl_template/model/err.tpl new file mode 100644 index 00000000..dc5eac4a --- /dev/null +++ b/goctl_template/model/err.tpl @@ -0,0 +1,5 @@ +package {{.pkg}} + +import "github.com/zeromicro/go-zero/core/stores/sqlx" + +var ErrNotFound = sqlx.ErrNotFound diff --git a/goctl_template/model/field.tpl b/goctl_template/model/field.tpl new file mode 100644 index 00000000..6b4ed387 --- /dev/null +++ b/goctl_template/model/field.tpl @@ -0,0 +1 @@ +{{.name}} {{.type}} {{.tag}} {{if .hasComment}}// {{.comment}}{{end}} \ No newline at end of file diff --git a/goctl_template/model/find-one-by-field-extra-method.tpl b/goctl_template/model/find-one-by-field-extra-method.tpl new file mode 100644 index 00000000..7e1df69d --- /dev/null +++ b/goctl_template/model/find-one-by-field-extra-method.tpl @@ -0,0 +1,8 @@ +func (m *default{{.upperStartCamelObject}}Model) formatPrimary(primary any) string { + return fmt.Sprintf("%s%v", {{.primaryKeyLeft}}, primary) +} + +func (m *default{{.upperStartCamelObject}}Model) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error { + query := fmt.Sprintf("select %s from %s where {{.originalPrimaryField}} = {{if .postgreSql}}$1{{else}}?{{end}} limit 1", {{.lowerStartCamelObject}}Rows, m.table ) + return conn.QueryRowCtx(ctx, v, query, primary) +} diff --git a/goctl_template/model/find-one-by-field.tpl b/goctl_template/model/find-one-by-field.tpl new file mode 100644 index 00000000..390fb01c --- /dev/null +++ b/goctl_template/model/find-one-by-field.tpl @@ -0,0 +1,30 @@ +func (m *default{{.upperStartCamelObject}}Model) FindOneBy{{.upperField}}(ctx context.Context, {{.in}}) (*{{.upperStartCamelObject}}, error) { + {{if .withCache}}{{.cacheKey}} + var resp {{.upperStartCamelObject}} + err := m.QueryRowIndexCtx(ctx, &resp, {{.cacheKeyVariable}}, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) { + query := fmt.Sprintf("select %s from %s where {{.originalField}} limit 1", {{.lowerStartCamelObject}}Rows, m.table) + if err := conn.QueryRowCtx(ctx, &resp, query, {{.lowerStartCamelField}}); err != nil { + return nil, err + } + return resp.{{.upperStartCamelPrimaryKey}}, nil + }, m.queryPrimary) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +}{{else}}var resp {{.upperStartCamelObject}} + query := fmt.Sprintf("select %s from %s where {{.originalField}} limit 1", {{.lowerStartCamelObject}}Rows, m.table ) + err := m.conn.QueryRowCtx(ctx, &resp, query, {{.lowerStartCamelField}}) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +}{{end}} diff --git a/goctl_template/model/find-one.tpl b/goctl_template/model/find-one.tpl new file mode 100644 index 00000000..a8085580 --- /dev/null +++ b/goctl_template/model/find-one.tpl @@ -0,0 +1,26 @@ +func (m *default{{.upperStartCamelObject}}Model) FindOne(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) (*{{.upperStartCamelObject}}, error) { + {{if .withCache}}{{.cacheKey}} + var resp {{.upperStartCamelObject}} + err := m.QueryRowCtx(ctx, &resp, {{.cacheKeyVariable}}, func(ctx context.Context, conn sqlx.SqlConn, v any) error { + query := fmt.Sprintf("select %s from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}} limit 1", {{.lowerStartCamelObject}}Rows, m.table) + return conn.QueryRowCtx(ctx, v, query, {{.lowerStartCamelPrimaryKey}}) + }) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + }{{else}}query := fmt.Sprintf("select %s from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}} limit 1", {{.lowerStartCamelObject}}Rows, m.table) + var resp {{.upperStartCamelObject}} + err := m.conn.QueryRowCtx(ctx, &resp, query, {{.lowerStartCamelPrimaryKey}}) + switch err { + case nil: + return &resp, nil + case sqlc.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + }{{end}} +} diff --git a/goctl_template/model/import-no-cache.tpl b/goctl_template/model/import-no-cache.tpl new file mode 100644 index 00000000..d99564e1 --- /dev/null +++ b/goctl_template/model/import-no-cache.tpl @@ -0,0 +1,13 @@ +import ( + "context" + "database/sql" + "fmt" + "strings" + {{if .time}}"time"{{end}} + + {{if .containsPQ}}"github.com/lib/pq"{{end}} + "github.com/zeromicro/go-zero/core/stores/builder" + "github.com/zeromicro/go-zero/core/stores/sqlc" + "github.com/zeromicro/go-zero/core/stores/sqlx" + "github.com/zeromicro/go-zero/core/stringx" +) diff --git a/goctl_template/model/import.tpl b/goctl_template/model/import.tpl new file mode 100644 index 00000000..7e0c40f5 --- /dev/null +++ b/goctl_template/model/import.tpl @@ -0,0 +1,14 @@ +import ( + "context" + "database/sql" + "fmt" + "strings" + {{if .time}}"time"{{end}} + + {{if .containsPQ}}"github.com/lib/pq"{{end}} + "github.com/zeromicro/go-zero/core/stores/builder" + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/core/stores/sqlc" + "github.com/zeromicro/go-zero/core/stores/sqlx" + "github.com/zeromicro/go-zero/core/stringx" +) diff --git a/goctl_template/model/insert.tpl b/goctl_template/model/insert.tpl new file mode 100644 index 00000000..08e02bce --- /dev/null +++ b/goctl_template/model/insert.tpl @@ -0,0 +1,9 @@ +func (m *default{{.upperStartCamelObject}}Model) Insert(ctx context.Context, data *{{.upperStartCamelObject}}) (sql.Result,error) { + {{if .withCache}}{{.keys}} + ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet) + return conn.ExecCtx(ctx, query, {{.expressionValues}}) + }, {{.keyValues}}){{else}}query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet) + ret,err:=m.conn.ExecCtx(ctx, query, {{.expressionValues}}){{end}} + return ret,err +} diff --git a/goctl_template/model/interface-delete.tpl b/goctl_template/model/interface-delete.tpl new file mode 100644 index 00000000..d10978b9 --- /dev/null +++ b/goctl_template/model/interface-delete.tpl @@ -0,0 +1 @@ +Delete(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) error \ No newline at end of file diff --git a/goctl_template/model/interface-find-one-by-field.tpl b/goctl_template/model/interface-find-one-by-field.tpl new file mode 100644 index 00000000..e18ded7a --- /dev/null +++ b/goctl_template/model/interface-find-one-by-field.tpl @@ -0,0 +1 @@ +FindOneBy{{.upperField}}(ctx context.Context, {{.in}}) (*{{.upperStartCamelObject}}, error) \ No newline at end of file diff --git a/goctl_template/model/interface-find-one.tpl b/goctl_template/model/interface-find-one.tpl new file mode 100644 index 00000000..a7a54401 --- /dev/null +++ b/goctl_template/model/interface-find-one.tpl @@ -0,0 +1 @@ +FindOne(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) (*{{.upperStartCamelObject}}, error) \ No newline at end of file diff --git a/goctl_template/model/interface-insert.tpl b/goctl_template/model/interface-insert.tpl new file mode 100644 index 00000000..28724037 --- /dev/null +++ b/goctl_template/model/interface-insert.tpl @@ -0,0 +1 @@ +Insert(ctx context.Context, data *{{.upperStartCamelObject}}) (sql.Result,error) \ No newline at end of file diff --git a/goctl_template/model/interface-update.tpl b/goctl_template/model/interface-update.tpl new file mode 100644 index 00000000..1920425d --- /dev/null +++ b/goctl_template/model/interface-update.tpl @@ -0,0 +1 @@ +Update(ctx context.Context, {{if .containsIndexCache}}newData{{else}}data{{end}} *{{.upperStartCamelObject}}) error \ No newline at end of file diff --git a/goctl_template/model/model-gen.tpl b/goctl_template/model/model-gen.tpl new file mode 100644 index 00000000..cc3b5954 --- /dev/null +++ b/goctl_template/model/model-gen.tpl @@ -0,0 +1,13 @@ +// Code generated by goctl. DO NOT EDIT. + +package {{.pkg}} +{{.imports}} +{{.vars}} +{{.types}} +{{.new}} +{{.delete}} +{{.find}} +{{.insert}} +{{.update}} +{{.extraMethod}} +{{.tableName}} diff --git a/goctl_template/model/model-new.tpl b/goctl_template/model/model-new.tpl new file mode 100644 index 00000000..76598ecd --- /dev/null +++ b/goctl_template/model/model-new.tpl @@ -0,0 +1,6 @@ +func new{{.upperStartCamelObject}}Model(conn sqlx.SqlConn{{if .withCache}}, c cache.CacheConf, opts ...cache.Option{{end}}) *default{{.upperStartCamelObject}}Model { + return &default{{.upperStartCamelObject}}Model{ + {{if .withCache}}CachedConn: sqlc.NewConn(conn, c, opts...){{else}}conn:conn{{end}}, + table: {{.table}}, + } +} diff --git a/goctl_template/model/model.tpl b/goctl_template/model/model.tpl new file mode 100644 index 00000000..3b1b1013 --- /dev/null +++ b/goctl_template/model/model.tpl @@ -0,0 +1,30 @@ +package {{.pkg}} +{{if .withCache}} +import ( + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/core/stores/sqlx" +) +{{else}} + +import "github.com/zeromicro/go-zero/core/stores/sqlx" +{{end}} +var _ {{.upperStartCamelObject}}Model = (*custom{{.upperStartCamelObject}}Model)(nil) + +type ( + // {{.upperStartCamelObject}}Model is an interface to be customized, add more methods here, + // and implement the added methods in custom{{.upperStartCamelObject}}Model. + {{.upperStartCamelObject}}Model interface { + {{.lowerStartCamelObject}}Model + } + + custom{{.upperStartCamelObject}}Model struct { + *default{{.upperStartCamelObject}}Model + } +) + +// New{{.upperStartCamelObject}}Model returns a model for the database table. +func New{{.upperStartCamelObject}}Model(conn sqlx.SqlConn{{if .withCache}}, c cache.CacheConf, opts ...cache.Option{{end}}) {{.upperStartCamelObject}}Model { + return &custom{{.upperStartCamelObject}}Model{ + default{{.upperStartCamelObject}}Model: new{{.upperStartCamelObject}}Model(conn{{if .withCache}}, c, opts...{{end}}), + } +} diff --git a/goctl_template/model/table-name.tpl b/goctl_template/model/table-name.tpl new file mode 100644 index 00000000..8b14e33a --- /dev/null +++ b/goctl_template/model/table-name.tpl @@ -0,0 +1,3 @@ +func (m *default{{.upperStartCamelObject}}Model) tableName() string { + return m.table +} diff --git a/goctl_template/model/tag.tpl b/goctl_template/model/tag.tpl new file mode 100644 index 00000000..8e1ddf0d --- /dev/null +++ b/goctl_template/model/tag.tpl @@ -0,0 +1 @@ +`db:"{{.field}}"` \ No newline at end of file diff --git a/goctl_template/model/types.tpl b/goctl_template/model/types.tpl new file mode 100644 index 00000000..960cf2b3 --- /dev/null +++ b/goctl_template/model/types.tpl @@ -0,0 +1,14 @@ +type ( + {{.lowerStartCamelObject}}Model interface{ + {{.method}} + } + + default{{.upperStartCamelObject}}Model struct { + {{if .withCache}}sqlc.CachedConn{{else}}conn sqlx.SqlConn{{end}} + table string + } + + {{.upperStartCamelObject}} struct { + {{.fields}} + } +) diff --git a/goctl_template/model/update.tpl b/goctl_template/model/update.tpl new file mode 100644 index 00000000..41b9331c --- /dev/null +++ b/goctl_template/model/update.tpl @@ -0,0 +1,14 @@ +func (m *default{{.upperStartCamelObject}}Model) Update(ctx context.Context, {{if .containsIndexCache}}newData{{else}}data{{end}} *{{.upperStartCamelObject}}) error { + {{if .withCache}}{{if .containsIndexCache}}data, err:=m.FindOne(ctx, newData.{{.upperStartCamelPrimaryKey}}) + if err!=nil{ + return err + } + +{{end}} {{.keys}} + _, {{if .containsIndexCache}}err{{else}}err:{{end}}= m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) { + query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder) + return conn.ExecCtx(ctx, query, {{.expressionValues}}) + }, {{.keyValues}}){{else}}query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder) + _,err:=m.conn.ExecCtx(ctx, query, {{.expressionValues}}){{end}} + return err +} diff --git a/goctl_template/model/var.tpl b/goctl_template/model/var.tpl new file mode 100644 index 00000000..c11fe535 --- /dev/null +++ b/goctl_template/model/var.tpl @@ -0,0 +1,8 @@ +var ( +{{.lowerStartCamelObject}}FieldNames = builder.RawFieldNames(&{{.upperStartCamelObject}}{}{{if .postgreSql}}, true{{end}}) +{{.lowerStartCamelObject}}Rows = strings.Join({{.lowerStartCamelObject}}FieldNames, ",") +{{.lowerStartCamelObject}}RowsExpectAutoSet = {{if .postgreSql}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, {{if .autoIncrement}}"{{.originalPrimaryKey}}", {{end}} {{.ignoreColumns}}), ","){{else}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, {{if .autoIncrement}}"{{.originalPrimaryKey}}", {{end}} {{.ignoreColumns}}), ","){{end}} +{{.lowerStartCamelObject}}RowsWithPlaceHolder = {{if .postgreSql}}builder.PostgreSqlJoin(stringx.Remove({{.lowerStartCamelObject}}FieldNames, "{{.originalPrimaryKey}}", {{.ignoreColumns}})){{else}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, "{{.originalPrimaryKey}}", {{.ignoreColumns}}), "=?,") + "=?"{{end}} + +{{if .withCache}}{{.cacheKeys}}{{end}} +) diff --git a/goctl_template/mongo/err.tpl b/goctl_template/mongo/err.tpl new file mode 100644 index 00000000..27d92449 --- /dev/null +++ b/goctl_template/mongo/err.tpl @@ -0,0 +1,12 @@ +package model + +import ( + "errors" + + "github.com/zeromicro/go-zero/core/stores/mon" +) + +var ( + ErrNotFound = mon.ErrNotFound + ErrInvalidObjectId = errors.New("invalid objectId") +) diff --git a/goctl_template/mongo/model.tpl b/goctl_template/mongo/model.tpl new file mode 100644 index 00000000..287125d9 --- /dev/null +++ b/goctl_template/mongo/model.tpl @@ -0,0 +1,78 @@ +// Code generated by goctl. DO NOT EDIT. +package model + +import ( + "context" + "time" + + {{if .Cache}}"github.com/zeromicro/go-zero/core/stores/monc"{{else}}"github.com/zeromicro/go-zero/core/stores/mon"{{end}} + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" +) + +{{if .Cache}}var prefix{{.Type}}CacheKey = "cache:{{.lowerType}}:"{{end}} + +type {{.lowerType}}Model interface{ + Insert(ctx context.Context,data *{{.Type}}) error + FindOne(ctx context.Context,id string) (*{{.Type}}, error) + Update(ctx context.Context,data *{{.Type}}) (*mongo.UpdateResult, error) + Delete(ctx context.Context,id string) (int64, error) +} + +type default{{.Type}}Model struct { + conn {{if .Cache}}*monc.Model{{else}}*mon.Model{{end}} +} + +func newDefault{{.Type}}Model(conn {{if .Cache}}*monc.Model{{else}}*mon.Model{{end}}) *default{{.Type}}Model { + return &default{{.Type}}Model{conn: conn} +} + + +func (m *default{{.Type}}Model) Insert(ctx context.Context, data *{{.Type}}) error { + if data.ID.IsZero() { + data.ID = primitive.NewObjectID() + data.CreateAt = time.Now() + data.UpdateAt = time.Now() + } + + {{if .Cache}}key := prefix{{.Type}}CacheKey + data.ID.Hex(){{end}} + _, err := m.conn.InsertOne(ctx, {{if .Cache}}key, {{end}} data) + return err +} + +func (m *default{{.Type}}Model) FindOne(ctx context.Context, id string) (*{{.Type}}, error) { + oid, err := primitive.ObjectIDFromHex(id) + if err != nil { + return nil, ErrInvalidObjectId + } + + var data {{.Type}} + {{if .Cache}}key := prefix{{.Type}}CacheKey + id{{end}} + err = m.conn.FindOne(ctx, {{if .Cache}}key, {{end}}&data, bson.M{"_id": oid}) + switch err { + case nil: + return &data, nil + case {{if .Cache}}monc{{else}}mon{{end}}.ErrNotFound: + return nil, ErrNotFound + default: + return nil, err + } +} + +func (m *default{{.Type}}Model) Update(ctx context.Context, data *{{.Type}}) (*mongo.UpdateResult, error) { + data.UpdateAt = time.Now() + {{if .Cache}}key := prefix{{.Type}}CacheKey + data.ID.Hex(){{end}} + res, err := m.conn.UpdateOne(ctx, {{if .Cache}}key, {{end}}bson.M{"_id": data.ID}, bson.M{"$set": data}) + return res, err +} + +func (m *default{{.Type}}Model) Delete(ctx context.Context, id string) (int64, error) { + oid, err := primitive.ObjectIDFromHex(id) + if err != nil { + return 0, ErrInvalidObjectId + } + {{if .Cache}}key := prefix{{.Type}}CacheKey +id{{end}} + res, err := m.conn.DeleteOne(ctx, {{if .Cache}}key, {{end}}bson.M{"_id": oid}) + return res, err +} diff --git a/goctl_template/mongo/model_custom.tpl b/goctl_template/mongo/model_custom.tpl new file mode 100644 index 00000000..31fa8653 --- /dev/null +++ b/goctl_template/mongo/model_custom.tpl @@ -0,0 +1,38 @@ +package model + +{{if .Cache}}import ( + "github.com/zeromicro/go-zero/core/stores/cache" + "github.com/zeromicro/go-zero/core/stores/monc" +){{else}}import "github.com/zeromicro/go-zero/core/stores/mon"{{end}} + +{{if .Easy}} +const {{.Type}}CollectionName = "{{.snakeType}}" +{{end}} + +var _ {{.Type}}Model = (*custom{{.Type}}Model)(nil) + +type ( + // {{.Type}}Model is an interface to be customized, add more methods here, + // and implement the added methods in custom{{.Type}}Model. + {{.Type}}Model interface { + {{.lowerType}}Model + } + + custom{{.Type}}Model struct { + *default{{.Type}}Model + } +) + + +// New{{.Type}}Model returns a model for the mongo. +{{if .Easy}}func New{{.Type}}Model(url, db string{{if .Cache}}, c cache.CacheConf{{end}}) {{.Type}}Model { + conn := {{if .Cache}}monc{{else}}mon{{end}}.MustNewModel(url, db, {{.Type}}CollectionName{{if .Cache}}, c{{end}}) + return &custom{{.Type}}Model{ + default{{.Type}}Model: newDefault{{.Type}}Model(conn), + } +}{{else}}func New{{.Type}}Model(url, db, collection string{{if .Cache}}, c cache.CacheConf{{end}}) {{.Type}}Model { + conn := {{if .Cache}}monc{{else}}mon{{end}}.MustNewModel(url, db, collection{{if .Cache}}, c{{end}}) + return &custom{{.Type}}Model{ + default{{.Type}}Model: newDefault{{.Type}}Model(conn), + } +}{{end}} diff --git a/goctl_template/mongo/model_types.tpl b/goctl_template/mongo/model_types.tpl new file mode 100644 index 00000000..8da006f4 --- /dev/null +++ b/goctl_template/mongo/model_types.tpl @@ -0,0 +1,14 @@ +package model + +import ( + "time" + + "go.mongodb.org/mongo-driver/bson/primitive" +) + +type {{.Type}} struct { + ID primitive.ObjectID `bson:"_id,omitempty" json:"id,omitempty"` + // TODO: Fill your own fields + UpdateAt time.Time `bson:"updateAt,omitempty" json:"updateAt,omitempty"` + CreateAt time.Time `bson:"createAt,omitempty" json:"createAt,omitempty"` +} diff --git a/goctl_template/newapi/newtemplate.tpl b/goctl_template/newapi/newtemplate.tpl new file mode 100644 index 00000000..28be5100 --- /dev/null +++ b/goctl_template/newapi/newtemplate.tpl @@ -0,0 +1,12 @@ +type Request { + Name string `path:"name,options=you|me"` +} + +type Response { + Message string `json:"message"` +} + +service {{.name}}-api { + @handler {{.handler}}Handler + get /from/:name(Request) returns (Response) +} diff --git a/goctl_template/rpc/call.tpl b/goctl_template/rpc/call.tpl new file mode 100644 index 00000000..27b48796 --- /dev/null +++ b/goctl_template/rpc/call.tpl @@ -0,0 +1,33 @@ +{{.head}} + +package {{.filePackage}} + +import ( + "context" + + {{.pbPackage}} + {{if ne .pbPackage .protoGoPackage}}{{.protoGoPackage}}{{end}} + + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" +) + +type ( + {{.alias}} + + {{.serviceName}} interface { + {{.interface}} + } + + default{{.serviceName}} struct { + cli zrpc.Client + } +) + +func New{{.serviceName}}(cli zrpc.Client) {{.serviceName}} { + return &default{{.serviceName}}{ + cli: cli, + } +} + +{{.functions}} diff --git a/goctl_template/rpc/config.tpl b/goctl_template/rpc/config.tpl new file mode 100644 index 00000000..c1f85b99 --- /dev/null +++ b/goctl_template/rpc/config.tpl @@ -0,0 +1,7 @@ +package config + +import "github.com/zeromicro/go-zero/zrpc" + +type Config struct { + zrpc.RpcServerConf +} diff --git a/goctl_template/rpc/etc.tpl b/goctl_template/rpc/etc.tpl new file mode 100644 index 00000000..6cd4bddf --- /dev/null +++ b/goctl_template/rpc/etc.tpl @@ -0,0 +1,6 @@ +Name: {{.serviceName}}.rpc +ListenOn: 0.0.0.0:8080 +Etcd: + Hosts: + - 127.0.0.1:2379 + Key: {{.serviceName}}.rpc diff --git a/goctl_template/rpc/logic-func.tpl b/goctl_template/rpc/logic-func.tpl new file mode 100644 index 00000000..e9410d41 --- /dev/null +++ b/goctl_template/rpc/logic-func.tpl @@ -0,0 +1,6 @@ +{{if .hasComment}}{{.comment}}{{end}} +func (l *{{.logicName}}) {{.method}} ({{if .hasReq}}in {{.request}}{{if .stream}},stream {{.streamBody}}{{end}}{{else}}stream {{.streamBody}}{{end}}) ({{if .hasReply}}{{.response}},{{end}} error) { + // todo: add your logic here and delete this line + + return {{if .hasReply}}&{{.responseType}}{},{{end}} nil +} diff --git a/goctl_template/rpc/logic.tpl b/goctl_template/rpc/logic.tpl new file mode 100644 index 00000000..b8d81f0b --- /dev/null +++ b/goctl_template/rpc/logic.tpl @@ -0,0 +1,24 @@ +package {{.packageName}} + +import ( + "context" + + {{.imports}} + + "github.com/zeromicro/go-zero/core/logx" +) + +type {{.logicName}} struct { + ctx context.Context + svcCtx *svc.ServiceContext + logx.Logger +} + +func New{{.logicName}}(ctx context.Context,svcCtx *svc.ServiceContext) *{{.logicName}} { + return &{{.logicName}}{ + ctx: ctx, + svcCtx: svcCtx, + Logger: logx.WithContext(ctx), + } +} +{{.functions}} diff --git a/goctl_template/rpc/main.tpl b/goctl_template/rpc/main.tpl new file mode 100644 index 00000000..58cb6760 --- /dev/null +++ b/goctl_template/rpc/main.tpl @@ -0,0 +1,36 @@ +package main + +import ( + "flag" + "fmt" + + {{.imports}} + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/core/service" + "github.com/zeromicro/go-zero/zrpc" + "google.golang.org/grpc" + "google.golang.org/grpc/reflection" +) + +var configFile = flag.String("f", "etc/{{.serviceName}}.yaml", "the config file") + +func main() { + flag.Parse() + + var c config.Config + conf.MustLoad(*configFile, &c) + ctx := svc.NewServiceContext(c) + + s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) { +{{range .serviceNames}} {{.Pkg}}.Register{{.Service}}Server(grpcServer, {{.ServerPkg}}.New{{.Service}}Server(ctx)) +{{end}} + if c.Mode == service.DevMode || c.Mode == service.TestMode { + reflection.Register(grpcServer) + } + }) + defer s.Stop() + + fmt.Printf("Starting rpc server at %s...\n", c.ListenOn) + s.Start() +} diff --git a/goctl_template/rpc/server-func.tpl b/goctl_template/rpc/server-func.tpl new file mode 100644 index 00000000..d771b438 --- /dev/null +++ b/goctl_template/rpc/server-func.tpl @@ -0,0 +1,6 @@ + +{{if .hasComment}}{{.comment}}{{end}} +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) { + l := {{.logicPkg}}.New{{.logicName}}({{if .notStream}}ctx,{{else}}stream.Context(),{{end}}s.svcCtx) + return l.{{.method}}({{if .hasReq}}in{{if .stream}} ,stream{{end}}{{else}}{{if .stream}}stream{{end}}{{end}}) +} diff --git a/goctl_template/rpc/server.tpl b/goctl_template/rpc/server.tpl new file mode 100644 index 00000000..84a2f9c1 --- /dev/null +++ b/goctl_template/rpc/server.tpl @@ -0,0 +1,22 @@ +{{.head}} + +package server + +import ( + {{if .notStream}}"context"{{end}} + + {{.imports}} +) + +type {{.server}}Server struct { + svcCtx *svc.ServiceContext + {{.unimplementedServer}} +} + +func New{{.server}}Server(svcCtx *svc.ServiceContext) *{{.server}}Server { + return &{{.server}}Server{ + svcCtx: svcCtx, + } +} + +{{.funcs}} diff --git a/goctl_template/rpc/svc.tpl b/goctl_template/rpc/svc.tpl new file mode 100644 index 00000000..cf2b47af --- /dev/null +++ b/goctl_template/rpc/svc.tpl @@ -0,0 +1,13 @@ +package svc + +import {{.imports}} + +type ServiceContext struct { + Config config.Config +} + +func NewServiceContext(c config.Config) *ServiceContext { + return &ServiceContext{ + Config:c, + } +} diff --git a/goctl_template/rpc/template.tpl b/goctl_template/rpc/template.tpl new file mode 100644 index 00000000..76daa944 --- /dev/null +++ b/goctl_template/rpc/template.tpl @@ -0,0 +1,16 @@ +syntax = "proto3"; + +package {{.package}}; +option go_package="./{{.package}}"; + +message Request { + string ping = 1; +} + +message Response { + string pong = 1; +} + +service {{.serviceName}} { + rpc Ping(Request) returns(Response); +} diff --git a/home-user-auth/etc/home-user-auth.yaml b/home-user-auth/etc/home-user-auth.yaml index 5129979b..d3abe90f 100644 --- a/home-user-auth/etc/home-user-auth.yaml +++ b/home-user-auth/etc/home-user-auth.yaml @@ -1,8 +1,7 @@ Name: home-user-auth Host: 0.0.0.0 Port: 8888 -DataSource: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest - +SourceMysql: fusentest:XErSYmLELKMnf3Dh@tcp(110.41.19.98:3306)/fusentest Auth: AccessSecret: fusen2023 diff --git a/home-user-auth/internal/config/config.go b/home-user-auth/internal/config/config.go index 1014355e..91e8781b 100644 --- a/home-user-auth/internal/config/config.go +++ b/home-user-auth/internal/config/config.go @@ -8,6 +8,6 @@ import ( type Config struct { rest.RestConf - DataSource string - Auth types.Auth + SourceMysql string + Auth types.Auth } diff --git a/home-user-auth/internal/handler/gettypehandler.go b/home-user-auth/internal/handler/gettypehandler.go index f4356da6..72416df1 100644 --- a/home-user-auth/internal/handler/gettypehandler.go +++ b/home-user-auth/internal/handler/gettypehandler.go @@ -1,28 +1,37 @@ package handler import ( + "errors" "net/http" + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + "fusenapi/home-user-auth/internal/logic" "fusenapi/home-user-auth/internal/svc" "fusenapi/home-user-auth/internal/types" - "github.com/zeromicro/go-zero/rest/httpx" ) func GetTypeHandler(svcCtx *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.ErrorCtx(r.Context(), w, err) + httpx.OkJsonCtx(r.Context(), w, &types.Response{ + Code: 510, + Message: "parameter error", + }) + logx.Info(err) return } l := logic.NewGetTypeLogic(r.Context(), svcCtx) - resp, err := l.GetType(&req) - if err != nil { - httpx.ErrorCtx(r.Context(), w, err) - } else { + resp := l.GetType(&req) + if resp != nil { httpx.OkJsonCtx(r.Context(), w, resp) + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) } } } diff --git a/home-user-auth/internal/handler/routes.go b/home-user-auth/internal/handler/routes.go index c1e264ee..09e53cbd 100644 --- a/home-user-auth/internal/handler/routes.go +++ b/home-user-auth/internal/handler/routes.go @@ -27,6 +27,11 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) { Path: "/user/get-type", Handler: GetTypeHandler(serverCtx), }, + { + Method: http.MethodPost, + Path: "/user/basic-info", + Handler: UserSaveBasicInfoHandler(serverCtx), + }, }, ) diff --git a/home-user-auth/internal/handler/userbasicinfohandler.go b/home-user-auth/internal/handler/userbasicinfohandler.go index d1c94b56..2534d8ab 100644 --- a/home-user-auth/internal/handler/userbasicinfohandler.go +++ b/home-user-auth/internal/handler/userbasicinfohandler.go @@ -1,29 +1,39 @@ package handler import ( + "errors" "net/http" + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + "fusenapi/home-user-auth/internal/logic" "fusenapi/home-user-auth/internal/svc" "fusenapi/home-user-auth/internal/types" - - "github.com/zeromicro/go-zero/rest/httpx" + "fusenapi/utils/auth" ) func UserBasicInfoHandler(svcCtx *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.ErrorCtx(r.Context(), w, err) + httpx.OkJsonCtx(r.Context(), w, &types.Response{ + Code: 510, + Message: "parameter error", + }) + logx.Info(err) return } l := logic.NewUserBasicInfoLogic(r.Context(), svcCtx) - resp, err := l.UserBasicInfo(&req) - if err != nil { - httpx.ErrorCtx(r.Context(), w, err) - } else { + userinfo := auth.CheckAuth(r) + resp := l.UserBasicInfo(&req, &userinfo) + if resp != nil { httpx.OkJsonCtx(r.Context(), w, resp) + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) } } } diff --git a/home-user-auth/internal/handler/userfontshandler.go b/home-user-auth/internal/handler/userfontshandler.go index 3598adf3..7b525cea 100644 --- a/home-user-auth/internal/handler/userfontshandler.go +++ b/home-user-auth/internal/handler/userfontshandler.go @@ -1,28 +1,37 @@ package handler import ( + "errors" "net/http" + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + "fusenapi/home-user-auth/internal/logic" "fusenapi/home-user-auth/internal/svc" "fusenapi/home-user-auth/internal/types" - "github.com/zeromicro/go-zero/rest/httpx" ) func UserFontsHandler(svcCtx *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.ErrorCtx(r.Context(), w, err) + httpx.OkJsonCtx(r.Context(), w, &types.Response{ + Code: 510, + Message: "parameter error", + }) + logx.Info(err) return } l := logic.NewUserFontsLogic(r.Context(), svcCtx) - resp, err := l.UserFonts(&req) - if err != nil { - httpx.ErrorCtx(r.Context(), w, err) - } else { + resp := l.UserFonts(&req) + if resp != nil { httpx.OkJsonCtx(r.Context(), w, resp) + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) } } } diff --git a/home-user-auth/internal/handler/userloginhandler.go b/home-user-auth/internal/handler/userloginhandler.go index 2a1fd67b..96c9eb95 100644 --- a/home-user-auth/internal/handler/userloginhandler.go +++ b/home-user-auth/internal/handler/userloginhandler.go @@ -1,28 +1,37 @@ package handler import ( + "errors" "net/http" + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + "fusenapi/home-user-auth/internal/logic" "fusenapi/home-user-auth/internal/svc" "fusenapi/home-user-auth/internal/types" - "github.com/zeromicro/go-zero/rest/httpx" ) func UserLoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req types.RequestUserLogin if err := httpx.Parse(r, &req); err != nil { - httpx.ErrorCtx(r.Context(), w, err) + httpx.OkJsonCtx(r.Context(), w, &types.Response{ + Code: 510, + Message: "parameter error", + }) + logx.Info(err) return } l := logic.NewUserLoginLogic(r.Context(), svcCtx) - resp, err := l.UserLogin(&req) - if err != nil { - httpx.ErrorCtx(r.Context(), w, err) - } else { + resp := l.UserLogin(&req) + if resp != nil { httpx.OkJsonCtx(r.Context(), w, resp) + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) } } } diff --git a/home-user-auth/internal/handler/usersavebasicinfohandler.go b/home-user-auth/internal/handler/usersavebasicinfohandler.go new file mode 100644 index 00000000..eb492e44 --- /dev/null +++ b/home-user-auth/internal/handler/usersavebasicinfohandler.go @@ -0,0 +1,39 @@ +package handler + +import ( + "errors" + "net/http" + + "github.com/zeromicro/go-zero/core/logx" + "github.com/zeromicro/go-zero/rest/httpx" + + "fusenapi/home-user-auth/internal/logic" + "fusenapi/home-user-auth/internal/svc" + "fusenapi/home-user-auth/internal/types" + "fusenapi/utils/auth" +) + +func UserSaveBasicInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req types.RequestBasicInfoForm + if err := httpx.Parse(r, &req); err != nil { + httpx.OkJsonCtx(r.Context(), w, &types.Response{ + Code: 510, + Message: "parameter error", + }) + logx.Info(err) + return + } + + l := logic.NewUserSaveBasicInfoLogic(r.Context(), svcCtx) + userinfo := auth.CheckAuth(r) + resp := l.UserSaveBasicInfo(&req, &userinfo) + if resp != nil { + httpx.OkJsonCtx(r.Context(), w, resp) + } else { + err := errors.New("server logic is error, resp must not be nil") + httpx.ErrorCtx(r.Context(), w, err) + logx.Error(err) + } + } +} diff --git a/home-user-auth/internal/logic/gettypelogic.go b/home-user-auth/internal/logic/gettypelogic.go index 9951edd2..99afc699 100644 --- a/home-user-auth/internal/logic/gettypelogic.go +++ b/home-user-auth/internal/logic/gettypelogic.go @@ -5,6 +5,8 @@ import ( "fusenapi/home-user-auth/internal/svc" "fusenapi/home-user-auth/internal/types" + "fusenapi/model" + "fusenapi/utils/basic" "github.com/zeromicro/go-zero/core/logx" ) @@ -23,19 +25,16 @@ func NewGetTypeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTypeLo } } -func (l *GetTypeLogic) GetType(req *types.Request) (resp *types.Response, err error) { - // todo: add your logic here and delete this line - data, err := l.svcCtx.FsCanteenTypeModel.FindGetType(l.ctx) +func (l *GetTypeLogic) GetType(req *types.Request) (resp *types.Response) { + // 必须返回response, 前端需要的是内部约定的Code码, 处理相关的逻辑. 例子(eg): resp.Set(501, "error") + resp = &types.Response{} + + data, err := model.NewFsCanteenTypeModel(l.svcCtx.MysqlConn).FindGetType(l.ctx) if err != nil { logx.Error(err) return } + resp.SetStatus(basic.StatusOK, "success", data) - // logx.Info(f) - resp = &types.Response{ - Code: 200, - Message: "success", - Data: data, - } - return + return resp } diff --git a/home-user-auth/internal/logic/userbasicinfologic.go b/home-user-auth/internal/logic/userbasicinfologic.go index 3493f24c..9d9841ad 100644 --- a/home-user-auth/internal/logic/userbasicinfologic.go +++ b/home-user-auth/internal/logic/userbasicinfologic.go @@ -5,6 +5,9 @@ import ( "fusenapi/home-user-auth/internal/svc" "fusenapi/home-user-auth/internal/types" + "fusenapi/model" + "fusenapi/utils/auth" + "fusenapi/utils/basic" "github.com/zeromicro/go-zero/core/logx" ) @@ -23,9 +26,25 @@ func NewUserBasicInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Use } } -func (l *UserBasicInfoLogic) UserBasicInfo(req *types.Request) (resp *types.Response, err error) { - // todo: add your logic here and delete this line +func (l *UserBasicInfoLogic) UserBasicInfo(req *types.Request, userinfo *auth.UserInfo) (resp *types.Response) { + // 必须返回response, 前端需要的是内部约定的Code码, 处理相关的逻辑. 例子(eg): resp.Set(501, "error") + resp = &types.Response{} - // l.svcCtx.FsUserModel.FindOne(l.ctx, ) - return + if userinfo.UserId == 0 { + resp = &types.Response{ + Code: 510, + Message: "user is not exists", + } + return resp + } + + fsUserModel, err := model.NewFsUserModel(l.svcCtx.MysqlConn).FindOne(l.ctx, userinfo.UserId) + if err != nil { + logx.Error(err) + resp.Set(510, err.Error()) + return resp + } + + resp.SetStatus(basic.StatusOK, fsUserModel) + return resp } diff --git a/home-user-auth/internal/logic/userfontslogic.go b/home-user-auth/internal/logic/userfontslogic.go index 495beb78..13feba28 100644 --- a/home-user-auth/internal/logic/userfontslogic.go +++ b/home-user-auth/internal/logic/userfontslogic.go @@ -5,6 +5,8 @@ import ( "fusenapi/home-user-auth/internal/svc" "fusenapi/home-user-auth/internal/types" + "fusenapi/model" + "fusenapi/utils/basic" "github.com/zeromicro/go-zero/core/logx" ) @@ -23,19 +25,18 @@ func NewUserFontsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserFon } } -func (l *UserFontsLogic) UserFonts(req *types.Request) (resp *types.Response, err error) { - // todo: add your logic here and delete this line - f, err := l.svcCtx.FsFontModel.FindAllOrderSortByDesc(l.ctx) +func (l *UserFontsLogic) UserFonts(req *types.Request) (resp *types.Response) { + // 必须返回response, 前端需要的是内部约定的Code码, 处理相关的逻辑. 例子(eg): resp.Set(501, "error") + resp = &types.Response{} + + data, err := model.NewFsFontModel(l.svcCtx.MysqlConn).FindAllOrderSortByDesc(l.ctx) if err != nil { // panic(err) logx.Error(err) - return + resp.SetStatus(basic.StatusOK, data) + return resp } - // logx.Info(f) - resp = &types.Response{ - Code: 200, - Message: "success", - Data: f, - } - return + + resp.SetStatus(basic.StatusOK) + return resp } diff --git a/home-user-auth/internal/logic/userloginlogic.go b/home-user-auth/internal/logic/userloginlogic.go index 10aee29f..fd0fa7ab 100644 --- a/home-user-auth/internal/logic/userloginlogic.go +++ b/home-user-auth/internal/logic/userloginlogic.go @@ -2,13 +2,12 @@ package logic import ( "context" - "log" "fusenapi/home-user-auth/internal/svc" "fusenapi/home-user-auth/internal/types" "fusenapi/model" + "fusenapi/utils/basic" - "github.com/golang-jwt/jwt/v4" "github.com/zeromicro/go-zero/core/logx" ) @@ -26,37 +25,21 @@ func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLog } } -func (l *UserLoginLogic) getJwtToken(secretKey string, iat, seconds, userId int64) (string, error) { - claims := make(jwt.MapClaims) - claims["exp"] = iat + seconds - claims["iat"] = iat - claims["userId"] = userId - token := jwt.New(jwt.SigningMethodHS256) - token.Claims = claims - return token.SignedString([]byte(secretKey)) -} +func (l *UserLoginLogic) UserLogin(req *types.RequestUserLogin) (resp *types.Response) { + // 必须返回response, 前端需要的是内部约定的Code码, 处理相关的逻辑. 例子(eg): resp.Set(501, "error") + resp = &types.Response{} -func (l *UserLoginLogic) UserLogin(req *types.RequestUserLogin) (resp *types.Response, err error) { - // todo: add your logic here and delete this line - data, err := l.svcCtx.FsUserModel.FindOneByEmail(l.ctx, req.Name) - // logx.Info(err.Error()) - log.Printf("%t %t %v", err, model.ErrNotFound, err == model.ErrNotFound) + userModel, err := model.NewFsUserModel(l.svcCtx.MysqlConn).FindOneByEmail(l.ctx, req.Name) + + // log.Printf("%t %t %v", err, model.ErrNotFound, err == model.ErrNotFound) if err == model.ErrNotFound { - // logx.Error(err) - resp = &types.Response{ - Code: 304, - Message: "fail", - } - return resp, nil + logx.Error(err) + resp.SetStatusWithMessage(basic.DefaultError, err.Error()) + return resp } - - resp = &types.Response{ - Code: 200, - Message: "success", - Data: &types.DataUserLogin{ - Token: data.PasswordResetToken.String, - }, + data := &types.DataUserLogin{ + Token: userModel.PasswordResetToken.String, } - - return resp, nil + resp.SetStatus(basic.StatusOK, data) + return resp } diff --git a/home-user-auth/internal/logic/usersavebasicinfologic.go b/home-user-auth/internal/logic/usersavebasicinfologic.go new file mode 100644 index 00000000..bebd9a58 --- /dev/null +++ b/home-user-auth/internal/logic/usersavebasicinfologic.go @@ -0,0 +1,45 @@ +package logic + +import ( + "context" + + "fusenapi/home-user-auth/internal/svc" + "fusenapi/home-user-auth/internal/types" + "fusenapi/model" + "fusenapi/utils/auth" + "fusenapi/utils/basic" + + "github.com/zeromicro/go-zero/core/logx" +) + +type UserSaveBasicInfoLogic struct { + logx.Logger + ctx context.Context + svcCtx *svc.ServiceContext +} + +func NewUserSaveBasicInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserSaveBasicInfoLogic { + return &UserSaveBasicInfoLogic{ + Logger: logx.WithContext(ctx), + ctx: ctx, + svcCtx: svcCtx, + } +} + +func (l *UserSaveBasicInfoLogic) UserSaveBasicInfo(req *types.RequestBasicInfoForm, userinfo *auth.UserInfo) (resp *types.Response) { + // 必须返回response, 前端需要的是内部约定的Code码, 处理相关的逻辑. 例子(eg): resp.Set(501, "error") + resp = &types.Response{} + // logx.Info(req) + if userinfo.UserId == 0 { + resp.SetStatusWithMessage(basic.DefaultError, "user is not exists") + return resp + } + + fsUserModel, err := model.NewFsUserModel(l.svcCtx.MysqlConn).FindOne(l.ctx, userinfo.UserId) + if err != nil { + logx.Error(err) + } + + resp.SetStatus(basic.StatusOK, fsUserModel) + return resp +} diff --git a/home-user-auth/internal/svc/servicecontext.go b/home-user-auth/internal/svc/servicecontext.go index a2cd6d8f..ae38bc4c 100644 --- a/home-user-auth/internal/svc/servicecontext.go +++ b/home-user-auth/internal/svc/servicecontext.go @@ -2,24 +2,18 @@ package svc import ( "fusenapi/home-user-auth/internal/config" - "fusenapi/model" - "github.com/zeromicro/go-zero/core/stores/sqlx" ) type ServiceContext struct { - Config config.Config - FsFontModel model.FsFontModel - FsCanteenTypeModel model.FsCanteenTypeModel - FsUserModel model.FsUserModel + Config config.Config + + MysqlConn sqlx.SqlConn } func NewServiceContext(c config.Config) *ServiceContext { - conn := sqlx.NewMysql(c.DataSource) return &ServiceContext{ - Config: c, - FsFontModel: model.NewFsFontModel(conn), - FsCanteenTypeModel: model.NewFsCanteenTypeModel(conn), - FsUserModel: model.NewFsUserModel(conn), + Config: c, + MysqlConn: sqlx.NewMysql(c.SourceMysql), } } diff --git a/home-user-auth/internal/types/types.go b/home-user-auth/internal/types/types.go index e6e3a5a4..d9fbc2b2 100644 --- a/home-user-auth/internal/types/types.go +++ b/home-user-auth/internal/types/types.go @@ -1,9 +1,30 @@ // Code generated by goctl. DO NOT EDIT. package types +import ( + "fusenapi/utils/basic" +) + type Request struct { } +type RequestBasicInfoForm struct { + FirstName string `form:"first_name,optional" db:"first_name"` // FirstName + LastName string `form:"last_name,optional" db:"last_name"` // LastName + Company string `form:"company,optional" db:"company"` // 公司名称 + Mobile string `form:"mobile,optional" db:"mobile"` // 手机号码 + Email string `form:"email" db:"email"` // 邮箱 + Status int64 `form:"status,optional" db:"status"` // 1正常 0不正常 + IsOrderStatusEmail int64 `form:"is_order_status_email,optional" db:"is_order_status_email"` // 订单状态改变时是否接收邮件 + IsEmailAdvertisement int64 `form:"is_email_advertisement,optional" db:"is_email_advertisement"` // 是否接收邮件广告 + IsOrderStatusPhone int64 `form:"is_order_status_phone,optional" db:"is_order_status_phone"` // 订单状态改变是是否接收电话 + IsPhoneAdvertisement int64 `form:"is_phone_advertisement,optional" db:"is_phone_advertisement"` // 是否接收短信广告 + IsOpenRender int64 `form:"is_open_render,optional" db:"is_open_render"` // 是否打开个性化渲染(1:开启,0:关闭) + IsLowRendering int64 `form:"is_low_rendering,optional" db:"is_low_rendering"` // 是否开启低渲染模型渲染 + IsRemoveBg int64 `form:"is_remove_bg,optional" db:"is_remove_bg"` // 用户上传logo是否去除背景 + NewPassword string `form:"new_password,optional" db:"new_password"` // new_password 如果存在新密码 +} + type RequestUserLogin struct { Name string `form:"name"` Password string `form:"pwd"` @@ -57,3 +78,49 @@ type Auth struct { AccessSecret string `json:"AccessSecret"` AccessExpire int `json:"AccessExpire"` } + +// Set 设置Response的Code和Message值 +func (resp *Response) Set(Code int, Message string) { + resp.Code = Code + resp.Message = Message +} + +// Set 设置整个Response +func (resp *Response) SetWithData(Code int, Message string, Data interface{}) { + resp.Code = Code + resp.Message = Message + resp.Data = Data +} + +// SetMessage 设置Response的Message +func (resp *Response) SetMessage(msg string) { + resp.Message = msg +} + +// SetWithData 设置Data +func (resp *Response) SetData(Data interface{}) { + resp.Data = Data +} + +// SetWithData 设置Response的Code和Message值 带Data入参数 +func (resp *Response) SetCode(Code int) { + resp.Code = Code +} + +// SetStatus 设置默认StatusResponse(内部自定义) 默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatus(sr *basic.StatusResponse, data ...interface{}) { + resp.Code = sr.Code + resp.Message = sr.Message + if len(data) == 1 { + resp.Data = data[0] + } +} + +// SetStatusWithMessage 设置默认StatusResponse(内部自定义) 非默认msg, 可以带data, data只使用一个参数 +func (resp *Response) SetStatusWithMessage(sr *basic.StatusResponse, msg string, data ...interface{}) { + resp.Code = sr.Code + resp.Message = msg + if len(data) == 1 { + resp.Data = data[0] + } +} diff --git a/model/fscanteentypemodel_gen.go b/model/fscanteentypemodel_gen.go index 5ec08874..4b4532a9 100755 --- a/model/fscanteentypemodel_gen.go +++ b/model/fscanteentypemodel_gen.go @@ -1,5 +1,3 @@ -// Code generated by goctl. DO NOT EDIT. - package model import ( @@ -15,8 +13,8 @@ import ( ) var ( - fsCanteenTypeFieldNames = builder.RawFieldNames(&FsCanteenType{}) - fsCanteenTypeRows = strings.Join(fsCanteenTypeFieldNames, ",") + fsCanteenTypeFieldNames = builder.RawFieldNames(&FsCanteenType{}) + fsCanteenTypeRows = strings.Join(fsCanteenTypeFieldNames, ",") // fsCanteenTypeGetTypeRows = strings.Join(stringx.Remove(fsCanteenTypeFieldNames, "`id`", "`name`", "`sort`", "`created_at`", "`status`"), ",") // fsCanteenTypeGetTypeRows = builder.RawFieldNames(&FsGetTypeCanteenType{}) fsCanteenTypeRowsExpectAutoSet = strings.Join(stringx.Remove(fsCanteenTypeFieldNames, "`id`", "`create_at`", "`create_time`", "`created_at`", "`update_at`", "`update_time`", "`updated_at`"), ",") @@ -29,7 +27,7 @@ type ( FindOne(ctx context.Context, id int64) (*FsCanteenType, error) Update(ctx context.Context, data *FsCanteenType) error Delete(ctx context.Context, id int64) error - + FindGetType(ctx context.Context) ([]*FsGetTypeCanteenType, error) } @@ -47,8 +45,8 @@ type ( } FsGetTypeCanteenType struct { - Id int64 `db:"id" json:"key"` // ID - Name string `db:"name" json:"name"` // 餐厅名字 + Id int64 `db:"id" json:"key"` // ID + Name string `db:"name" json:"name"` // 餐厅名字 } ) @@ -80,7 +78,7 @@ func (m *defaultFsCanteenTypeModel) FindOne(ctx context.Context, id int64) (*FsC } func (m *defaultFsCanteenTypeModel) FindGetType(ctx context.Context) ([]*FsGetTypeCanteenType, error) { - + query := fmt.Sprintf("select X.id,X.name from (select %s from %s where status = 1 order by sort desc) X", fsCanteenTypeRows, m.table) var resp []*FsGetTypeCanteenType err := m.conn.QueryRows(&resp, query) diff --git a/model/fsfontmodel_gen.go b/model/fsfontmodel_gen.go index be14369e..30021b69 100755 --- a/model/fsfontmodel_gen.go +++ b/model/fsfontmodel_gen.go @@ -72,6 +72,7 @@ func (m *defaultFsFontModel) FindOne(ctx context.Context, id int64) (*FsFont, er } func (m *defaultFsFontModel) FindAllOrderSortByDesc(ctx context.Context) ([]*FsFont, error) { + query := fmt.Sprintf("select %s from %s order by sort desc", fsFontRows, m.table) var resp []*FsFont err := m.conn.QueryRows(&resp, query) diff --git a/about-us.api b/server_api/about-us.api similarity index 100% rename from about-us.api rename to server_api/about-us.api diff --git a/basic.api b/server_api/basic.api similarity index 82% rename from basic.api rename to server_api/basic.api index cc95ae44..45de403b 100644 --- a/basic.api +++ b/server_api/basic.api @@ -7,13 +7,14 @@ info ( email: "" ) +// response 统一返回码 type response { Code int `json:"code"` Message string `json:"msg"` Data interface{} `json:"data"` } - +// Auth jwt认证认证的安全参数 type Auth { AccessSecret string `json:"AccessSecret"` AccessExpire int `json:"AccessExpire"` diff --git a/cloud-storage.api b/server_api/cloud-storage.api similarity index 100% rename from cloud-storage.api rename to server_api/cloud-storage.api diff --git a/contact-us.api b/server_api/contact-us.api similarity index 100% rename from contact-us.api rename to server_api/contact-us.api diff --git a/data-transfer.api b/server_api/data-transfer.api similarity index 100% rename from data-transfer.api rename to server_api/data-transfer.api diff --git a/designs.api b/server_api/designs.api similarity index 100% rename from designs.api rename to server_api/designs.api diff --git a/faq.api b/server_api/faq.api similarity index 100% rename from faq.api rename to server_api/faq.api diff --git a/home-user-auth.api b/server_api/home-user-auth.api similarity index 62% rename from home-user-auth.api rename to server_api/home-user-auth.api index 8435885f..bbcf7320 100644 --- a/home-user-auth.api +++ b/server_api/home-user-auth.api @@ -14,6 +14,24 @@ type request { // Name string `form:"name"` // parameters are auto validated } +type RequestBasicInfoForm { + FirstName string `form:"first_name,optional" db:"first_name"` // FirstName + LastName string `form:"last_name,optional" db:"last_name"` // LastName + Company string `form:"company,optional" db:"company"` // 公司名称 + Mobile string `form:"mobile,optional" db:"mobile"` // 手机号码 + Email string `form:"email" db:"email"` // 邮箱 + Status int64 `form:"status,optional" db:"status"` // 1正常 0不正常 + IsOrderStatusEmail int64 `form:"is_order_status_email,optional" db:"is_order_status_email"` // 订单状态改变时是否接收邮件 + IsEmailAdvertisement int64 `form:"is_email_advertisement,optional" db:"is_email_advertisement"` // 是否接收邮件广告 + IsOrderStatusPhone int64 `form:"is_order_status_phone,optional" db:"is_order_status_phone"` // 订单状态改变是是否接收电话 + IsPhoneAdvertisement int64 `form:"is_phone_advertisement,optional" db:"is_phone_advertisement"` // 是否接收短信广告 + IsOpenRender int64 `form:"is_open_render,optional" db:"is_open_render"` // 是否打开个性化渲染(1:开启,0:关闭) + IsLowRendering int64 `form:"is_low_rendering,optional" db:"is_low_rendering"` // 是否开启低渲染模型渲染 + IsRemoveBg int64 `form:"is_remove_bg,optional" db:"is_remove_bg"` // 用户上传logo是否去除背景 + + NewPassword string `form:"new_password,optional" db:"new_password"` // new_password 如果存在新密码 +} + // UserLoginHandler 用户登录请求结构 type RequestUserLogin { Name string `form:"name"` @@ -62,7 +80,6 @@ type DataGetType { } service home-user-auth { - @handler UserLoginHandler post /user/login(RequestUserLogin) returns (response); @@ -71,6 +88,9 @@ service home-user-auth { @handler GetTypeHandler get /user/get-type(request) returns (response); + + @handler UserSaveBasicInfoHandler + post /user/basic-info(RequestBasicInfoForm) returns (response); } @server( diff --git a/orders.api b/server_api/orders.api similarity index 100% rename from orders.api rename to server_api/orders.api diff --git a/product.api b/server_api/product.api similarity index 100% rename from product.api rename to server_api/product.api diff --git a/profile.api b/server_api/profile.api similarity index 100% rename from profile.api rename to server_api/profile.api diff --git a/shopping-cart-confirmation.api b/server_api/shopping-cart-confirmation.api similarity index 100% rename from shopping-cart-confirmation.api rename to server_api/shopping-cart-confirmation.api diff --git a/utils/basic/basic.go b/utils/basic/basic.go new file mode 100644 index 00000000..2ad50615 --- /dev/null +++ b/utils/basic/basic.go @@ -0,0 +1,12 @@ +package basic + +// StatusResponse 公司自定义状态码 +type StatusResponse struct { + Code int + Message string +} + +var ( + StatusOK = &StatusResponse{200, "success"} // 成功 + DefaultError = &StatusResponse{510, "unknown error"} // 错误 +)