first commit

This commit is contained in:
2025-09-21 18:27:25 +08:00
commit 02e1c4bd63
528 changed files with 55690 additions and 0 deletions

View File

@@ -0,0 +1,62 @@
# 设置输出编码为UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
# 数据库连接信息 - 修改了URL格式
$DB_URL = "hm:5vg67b3UNHu8@(127.0.0.1:21001)/hm"
$OUTPUT_DIR = "./model"
$TEMPLATE_DIR = "../template"
# 表名列表
$tables = @(
# "agent",
# "agent_active_stat",
# "agent_audit",
# "agent_closure",
# "agent_commission",
# "agent_commission_deduction",
# "agent_link",
# "agent_membership_config",
# "agent_membership_recharge_order"
# "agent_membership_user_config",
# "agent_order",
# "agent_platform_deduction",
# "agent_product_config",
# "agent_rewards",
# "agent_wallet",
# "agent_real_name"
# "agent_withdrawal"
"agent_withdrawal_tax"
# "agent_withdrawal_tax_exemption"
# "feature",
# "global_notifications"
# "order",
# "order_refund"
# "product",
# "product_feature",
# "query",
# "query_cleanup_log"
# "query_cleanup_detail"
# "query_cleanup_config"
# "user"
# "user_auth"
# "user_temp"
# "example"
# "admin_user"
# "admin_user_role"
# "admin_api",
# "admin_menu"
# "admin_role",
# "admin_role_api",
# "admin_role_menu",
# "admin_dict_data"
# "admin_dict_type"
# "admin_promotion_link"
# "admin_promotion_link_stats_total"
# "admin_promotion_link_stats_history"
# "admin_promotion_order"
)
# 为每个表生成模型
foreach ($table in $tables) {
goctl model mysql datasource -url="hm:5vg67b3UNHu8@tcp(127.0.0.1:21001)/hm" -table="$table" -dir="./model" --home="../template" -cache=true --style=goZero
}

View File

@@ -0,0 +1,9 @@
package model
import (
"errors"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var ErrNotFound = sqlx.ErrNotFound
var ErrNoRowsUpdate = errors.New("update db no rows change")

41
deploy/sql/order.sql Normal file
View File

@@ -0,0 +1,41 @@
CREATE TABLE `order` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`order_no` varchar(32) NOT NULL COMMENT '自生成的订单号',
`user_id` bigint NOT NULL COMMENT '用户ID',
`product_id` bigint NOT NULL COMMENT '产品ID软关联到产品表',
`payment_platform` enum(
'alipay',
'wechat',
'appleiap',
'other'
) NOT NULL COMMENT '支付平台(支付宝、微信、苹果内购、其他)',
`payment_scene` enum(
'app',
'h5',
'mini_program',
'public_account'
) NOT NULL COMMENT '支付场景App、H5、微信小程序、公众号',
`platform_order_id` varchar(64) DEFAULT NULL COMMENT '支付平台订单号',
`amount` decimal(10, 2) NOT NULL COMMENT '支付金额',
`status` enum(
'pending',
'paid',
'failed',
'refunded',
'closed'
) NOT NULL DEFAULT 'pending' COMMENT '支付状态',
`del_state` tinyint NOT NULL DEFAULT '0' COMMENT '删除状态',
`version` bigint NOT NULL DEFAULT '0' COMMENT '版本号',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`pay_time` datetime DEFAULT NULL COMMENT '支付时间',
`refund_time` datetime DEFAULT NULL COMMENT '退款时间',
`close_time` datetime DEFAULT NULL COMMENT '订单关闭时间',
`delete_time` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `unique_order_no` (`order_no`),
KEY `idx_user_id` (`user_id`),
KEY `idx_product_id` (`product_id`),
KEY `idx_payment_platform` (`payment_platform`),
KEY `idx_payment_scene` (`payment_scene`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '订单表';

116
deploy/sql/product.sql Normal file
View File

@@ -0,0 +1,116 @@
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`delete_time` datetime DEFAULT NULL COMMENT '删除时间',
`del_state` tinyint NOT NULL DEFAULT '0' COMMENT '删除状态',
`version` bigint NOT NULL DEFAULT '0' COMMENT '版本号',
`product_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '服务名',
`product_en` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '英文名',
`description` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '描述',
`notes` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '备注',
`cost_price` DECIMAL(10, 2) NOT NULL DEFAULT '1.00' COMMENT '成本',
`sell_price` DECIMAL(10, 2) NOT NULL DEFAULT '1.00' COMMENT '售价',
PRIMARY KEY (`id`),
UNIQUE KEY `unique_product_en` (`product_en`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='产品表';
-- ----------------------------
-- Records for product
-- ----------------------------
INSERT INTO `product` (`product_name`, `product_en`, `description`, `notes`, `cost_price`, `sell_price`) VALUES
('背景调查', 'backgroundchecklogic', '', '', 1, 1),
('企业报告', 'companyinfologic', '', '', 1, 1),
('家政服务', 'homeservicelogic', '', '', 1, 1),
('婚姻状态', 'marriagelogic', '', '', 1, 1),
('贷前背调', 'preloanbackgroundchecklogic', '', '', 1, 1),
('租赁服务', 'rentalinfologic', '', '', 1, 1),
('个人风险评估', 'riskassessmentlogic', '', '', 1, 1),
('手机三要素', 'toc_PhoneThreeElements', '', '', 1, 1),
('银行卡黑名单', 'toc_BankCardBlacklist', '', '', 1, 1),
('身份证二要素', 'toc_IDCardTwoElements', '', '', 1, 1),
('手机二要素', 'toc_PhoneTwoElements', '', '', 1, 1),
('在网时长', 'toc_NetworkDuration', '', '', 1, 1),
('手机二次卡', 'toc_PhoneSecondaryCard', '', '', 1, 1),
('手机号码风险', 'toc_PhoneNumberRisk', '', '', 1, 1),
('银行卡四要素', 'toc_BankCardFourElements', '', '', 1, 1),
('银行卡三要素', 'toc_BankCardThreeElements', '', '', 1, 1),
('自然人生存状态', 'toc_NaturalLifeStatus', '', '', 1, 1),
('学历核验', 'toc_EducationVerification', '', '', 1, 1),
('人车核验', 'toc_PersonVehicleVerification', '', '', 1, 1),
('名下车辆', 'toc_VehiclesUnderName', '', '', 1, 1),
('双人婚姻', 'toc_DualMarriage', '', '', 1, 1),
('个人不良', 'toc_PersonalBadRecord', '', '', 1, 1),
('股东人企关系', 'toc_ShareholderBusinessRelation', '', '', 1, 1),
('个人涉诉', 'toc_PersonalLawsuit', '', '', 1, 1),
('企业涉诉', 'toc_EnterpriseLawsuit', '', '', 1, 1),
('婚姻评估', 'toc_MarriageAssessment', '', '', 1, 1);
SET FOREIGN_KEY_CHECKS = 1;
-- ----------------------------
-- Table structure for feature
-- ----------------------------
DROP TABLE IF EXISTS `feature`;
CREATE TABLE `feature` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`delete_time` datetime DEFAULT NULL COMMENT '删除时间',
`del_state` tinyint NOT NULL DEFAULT '0' COMMENT '删除状态',
`version` bigint NOT NULL DEFAULT '0' COMMENT '版本号',
`api_id` varchar kujmio,5(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'API标识',
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '描述',
PRIMARY KEY (`id`),
UNIQUE KEY `unique_api_id` (`api_id`)``
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='功能表';
-- ----------------------------
-- Table structure for product_feature
-- ----------------------------
DROP TABLE IF EXISTS `product_feature`;
CREATE TABLE `product_feature` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`product_id` bigint NOT NULL COMMENT '产品ID',
`feature_id` bigint NOT NULL COMMENT '功能ID',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`delete_time` datetime DEFAULT NULL COMMENT '删除时间',
`del_state` tinyint NOT NULL DEFAULT '0' COMMENT '删除状态',
`version` bigint NOT NULL DEFAULT '0' COMMENT '版本号',
PRIMARY KEY (`id`),
UNIQUE KEY `unique_product_feature` (`product_id`, `feature_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='产品与功能关联表';
-- ----------------------------
-- Records for feature
-- ----------------------------
INSERT INTO `feature` (`api_id`, `name`) VALUES
('G09SC02', '单人婚姻'),
('G27BJ05', '借贷意向'),
('G28BJ05', '借贷行为'),
('G26BJ05', '特殊名单'),
('G34BJ03', '个人不良'),
('G35SC01', '个人涉诉'),
('G05HZ01', '股东人企关系');
-- ----------------------------
-- 插入每个产品与每个功能的对应关系
-- ----------------------------
INSERT INTO `product_feature` (`product_id`, `feature_id`)
SELECT
p.id AS product_id,
f.id AS feature_id
FROM
product p
CROSS JOIN
feature f;

18
deploy/sql/query.sql Normal file
View File

@@ -0,0 +1,18 @@
CREATE TABLE `query` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`order_id` BIGINT NOT NULL COMMENT '订单ID软关联到订单表',
`user_id` BIGINT NOT NULL COMMENT '用户ID直接关联到用户',
`product_id` BIGINT NOT NULL COMMENT '产品ID直接关联到产品',
`query_params` TEXT NOT NULL COMMENT '查询params数据',
`query_data` LONGTEXT COMMENT '查询结果数据',
`query_state` ENUM('pending', 'success', 'failed') NOT NULL DEFAULT 'pending' COMMENT '查询状态',
`del_state` TINYINT NOT NULL DEFAULT '0' COMMENT '删除状态',
`version` BIGINT NOT NULL DEFAULT '0' COMMENT '版本号',
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`delete_time` DATETIME DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `unique_order_id` (`order_id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='查询结果表,存储关联订单的查询数据';

20
deploy/sql/template.sql Normal file
View File

@@ -0,0 +1,20 @@
CREATE TABLE `` (
`id` bigint NOT NULL AUTO_INCREMENT,
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`delete_time` datetime DEFAULT NULL COMMENT '删除时间',
`del_state` tinyint NOT NULL DEFAULT '0',
`version` bigint NOT NULL DEFAULT '0' COMMENT '版本号',
/* 业务字段开始 */
`1` [] [DEFAULT ] [COMMENT '字段说明'],
`2` [] [DEFAULT ] [COMMENT '字段说明'],
/* 关联字段 - 软关联 */
`id` bigint [NOT NULL] [DEFAULT '0'] COMMENT '关联到XX表的id',
/* 业务字段结束 */
PRIMARY KEY (`id`),
/* 索引定义 */
UNIQUE KEY `` (``),
KEY `idx_关联字段` (`id`) COMMENT '优化关联查询'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='表说明';

43
deploy/sql/user.sql Normal file
View File

@@ -0,0 +1,43 @@
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for main
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint NOT NULL AUTO_INCREMENT,
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`delete_time` datetime DEFAULT NULL COMMENT '删除时间',
`del_state` tinyint NOT NULL DEFAULT '0',
`version` bigint NOT NULL DEFAULT '0' COMMENT '版本号',
`mobile` char(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
`nickname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
`info` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
`inside` tinyint NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `unique_mobile` (`mobile`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='用户表';
-- ----------------------------
-- Table structure for user_auth
-- ----------------------------
DROP TABLE IF EXISTS `user_auth`;
CREATE TABLE `user_auth` (
`id` bigint NOT NULL AUTO_INCREMENT,
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`delete_time` datetime DEFAULT NULL COMMENT '删除时间',
`del_state` tinyint NOT NULL DEFAULT '0',
`version` bigint NOT NULL DEFAULT '0' COMMENT '版本号',
`user_id` bigint NOT NULL DEFAULT '0',
`auth_key` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '平台唯一id',
`auth_type` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '平台类型',
PRIMARY KEY (`id`),
UNIQUE KEY `unique_type_key` (`auth_type`,`auth_key`) USING BTREE,
UNIQUE KEY `unique_userId_key` (`user_id`,`auth_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='用户授权表';
SET FOREIGN_KEY_CHECKS = 1;

View File

@@ -0,0 +1,9 @@
package config
import {{.authImport}}
type Config struct {
rest.RestConf
{{.auth}}
{{.jwtTrans}}
}

View File

@@ -0,0 +1,17 @@
package svc
import (
{{.configImport}}
)
type ServiceContext struct {
Config {{.config}}
{{.middleware}}
}
func NewServiceContext(c {{.config}}) *ServiceContext {
return &ServiceContext{
Config: c,
{{.middlewareAssignment}}
}
}

View File

@@ -0,0 +1,3 @@
Name: {{.serviceName}}
Host: {{.host}}
Port: {{.port}}

View File

@@ -0,0 +1,27 @@
package {{.PkgName}}
import (
"net/http"
"hm-server/common/result"
"hm-server/pkg/lzkit/validator"
"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 {
result.ParamErrorResult(r,w,err)
return
}
if err := validator.Validate(req); err != nil {
result.ParamValidateErrorResult(r, w, err)
return
}
{{end}}l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx)
{{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}&req{{end}})
result.HttpResult(r, w, {{if .HasResp}}resp{{else}}nil{{end}}, err)
}
}

View File

@@ -0,0 +1,25 @@
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}}) {{.responseType}} {
// todo: add your logic here and delete this line
{{.returnString}}
}

View File

@@ -0,0 +1,27 @@
package main
import (
"flag"
"fmt"
{{.importPackages}}
"hm-server/common/middleware"
)
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)
server := rest.MustNewServer(c.RestConf)
defer server.Stop()
handler.RegisterHandlers(server, ctx)
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
}

View File

@@ -0,0 +1,20 @@
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)
}
}

View File

@@ -0,0 +1,4 @@
server.AddRoutes(
{{.routes}} {{.jwt}}{{.signature}} {{.prefix}} {{.timeout}} {{.maxBytes}}
)

View File

@@ -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}}
}

View File

@@ -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)
}

View File

@@ -0,0 +1,6 @@
// Code generated by goctl. DO NOT EDIT.
package types{{if .containsTime}}
import (
"time"
){{end}}
{{.types}}

View File

@@ -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}}]

View File

@@ -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

View File

@@ -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()
}

View File

@@ -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

View File

@@ -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

View File

@@ -0,0 +1,21 @@
func (m *default{{.upperStartCamelObject}}Model) Delete(ctx context.Context, session sqlx.Session, {{.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)
if session!=nil{
return session.ExecCtx(ctx,query, {{.lowerStartCamelPrimaryKey}})
}
return conn.ExecCtx(ctx, query, {{.lowerStartCamelPrimaryKey}})
}, {{.keyValues}}){{else}}query := fmt.Sprintf("delete from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}}", m.table)
if session!=nil{
_,err:= session.ExecCtx(ctx,query, {{.lowerStartCamelPrimaryKey}})
return err
}
_,err:=m.conn.ExecCtx(ctx, query, {{.lowerStartCamelPrimaryKey}}){{end}}
return err
}

View File

@@ -0,0 +1,9 @@
package {{.pkg}}
import (
"errors"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var ErrNotFound = sqlx.ErrNotFound
var ErrNoRowsUpdate = errors.New("update db no rows change")

View File

@@ -0,0 +1 @@
{{.name}} {{.type}} {{.tag}} {{if .hasComment}}// {{.comment}}{{end}}

View File

@@ -0,0 +1,7 @@
func (m *default{{.upperStartCamelObject}}Model) formatPrimary(primary interface{}) string {
return fmt.Sprintf("%s%v", {{.primaryKeyLeft}}, primary)
}
func (m *default{{.upperStartCamelObject}}Model) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary interface{}) error {
query := fmt.Sprintf("select %s from %s where {{.originalPrimaryField}} = {{if .postgreSql}}$1{{else}}?{{end}} and del_state = ? limit 1", {{.lowerStartCamelObject}}Rows, m.table )
return conn.QueryRowCtx(ctx, v, query, primary,globalkey.DelStateNo)
}

View File

@@ -0,0 +1,32 @@
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 interface{}) (i interface{}, e error) {
query := fmt.Sprintf("select %s from %s where {{.originalField}} and del_state = ? limit 1", {{.lowerStartCamelObject}}Rows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, {{.lowerStartCamelField}},globalkey.DelStateNo); 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}} and del_state = ? limit 1", {{.lowerStartCamelObject}}Rows, m.table )
err := m.conn.QueryRowCtx(ctx, &resp, query, {{.lowerStartCamelField}},globalkey.DelStateNo)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}{{end}}

View File

@@ -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 interface{}) error {
query := fmt.Sprintf("select %s from %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}} and del_state = ? limit 1", {{.lowerStartCamelObject}}Rows, m.table)
return conn.QueryRowCtx(ctx, v, query, {{.lowerStartCamelPrimaryKey}},globalkey.DelStateNo)
})
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}} and del_state = ? limit 1", {{.lowerStartCamelObject}}Rows, m.table)
var resp {{.upperStartCamelObject}}
err := m.conn.QueryRowCtx(ctx, &resp, query, {{.lowerStartCamelPrimaryKey}},globalkey.DelStateNo)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}{{end}}
}

View File

@@ -0,0 +1,16 @@
import (
"context"
"database/sql"
"fmt"
"strings"
{{if .time}}"time"{{end}}
"hm-server/common/globalkey"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"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"
)

View File

@@ -0,0 +1,17 @@
import (
"context"
"database/sql"
"fmt"
"strings"
{{if .time}}"time"{{end}}
"hm-server/common/globalkey"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"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"
)

View File

@@ -0,0 +1,17 @@
func (m *default{{.upperStartCamelObject}}Model) Insert(ctx context.Context,session sqlx.Session, data *{{.upperStartCamelObject}}) (sql.Result,error) {
data.DelState = globalkey.DelStateNo
{{if .withCache}}{{.keys}}
return 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)
if session != nil{
return session.ExecCtx(ctx,query,{{.expressionValues}})
}
return conn.ExecCtx(ctx, query, {{.expressionValues}})
}, {{.keyValues}}){{else}}
query := fmt.Sprintf("insert into %s (%s) values ({{.expression}})", m.table, {{.lowerStartCamelObject}}RowsExpectAutoSet)
if session != nil{
return session.ExecCtx(ctx,query,{{.expressionValues}})
}
return m.conn.ExecCtx(ctx, query, {{.expressionValues}}){{end}}
}

View File

@@ -0,0 +1 @@
Delete(ctx context.Context,session sqlx.Session, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) error

View File

@@ -0,0 +1 @@
FindOneBy{{.upperField}}(ctx context.Context, {{.in}}) (*{{.upperStartCamelObject}}, error)

View File

@@ -0,0 +1 @@
FindOne(ctx context.Context, {{.lowerStartCamelPrimaryKey}} {{.dataType}}) (*{{.upperStartCamelObject}}, error)

View File

@@ -0,0 +1 @@
Insert(ctx context.Context, session sqlx.Session,data *{{.upperStartCamelObject}}) (sql.Result,error)

View File

@@ -0,0 +1,12 @@
Update(ctx context.Context,session sqlx.Session, data *{{.upperStartCamelObject}}) (sql.Result, error)
UpdateWithVersion(ctx context.Context,session sqlx.Session,data *{{.upperStartCamelObject}}) error
Trans(ctx context.Context,fn func(context context.Context,session sqlx.Session) error) error
SelectBuilder() squirrel.SelectBuilder
DeleteSoft(ctx context.Context,session sqlx.Session, data *{{.upperStartCamelObject}}) error
FindSum(ctx context.Context,sumBuilder squirrel.SelectBuilder,field string) (float64,error)
FindCount(ctx context.Context,countBuilder squirrel.SelectBuilder,field string) (int64,error)
FindAll(ctx context.Context,rowBuilder squirrel.SelectBuilder,orderBy string) ([]*{{.upperStartCamelObject}},error)
FindPageListByPage(ctx context.Context,rowBuilder squirrel.SelectBuilder,page ,pageSize int64,orderBy string) ([]*{{.upperStartCamelObject}},error)
FindPageListByPageWithTotal(ctx context.Context, rowBuilder squirrel.SelectBuilder, page, pageSize int64, orderBy string) ([]*{{.upperStartCamelObject}}, int64, error)
FindPageListByIdDESC(ctx context.Context,rowBuilder squirrel.SelectBuilder ,preMinId ,pageSize int64) ([]*{{.upperStartCamelObject}},error)
FindPageListByIdASC(ctx context.Context,rowBuilder squirrel.SelectBuilder,preMaxId ,pageSize int64) ([]*{{.upperStartCamelObject}},error)

View File

@@ -0,0 +1,13 @@
// Code generated by goctl. DO NOT EDIT!
package {{.pkg}}
{{.imports}}
{{.vars}}
{{.types}}
{{.new}}
{{.insert}}
{{.find}}
{{.update}}
{{.delete}}
{{.extraMethod}}
{{.tableName}}

View File

@@ -0,0 +1,7 @@
func new{{.upperStartCamelObject}}Model(conn sqlx.SqlConn{{if .withCache}}, c cache.CacheConf{{end}}) *default{{.upperStartCamelObject}}Model {
return &default{{.upperStartCamelObject}}Model{
{{if .withCache}}CachedConn: sqlc.NewConn(conn, c){{else}}conn:conn{{end}},
table: {{.table}},
}
}

View File

@@ -0,0 +1,37 @@
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{{end}}) {{.upperStartCamelObject}}Model {
return &custom{{.upperStartCamelObject}}Model{
default{{.upperStartCamelObject}}Model: new{{.upperStartCamelObject}}Model(conn{{if .withCache}}, c{{end}}),
}
}

View File

@@ -0,0 +1,4 @@
func (m *default{{.upperStartCamelObject}}Model) tableName() string {
return m.table
}

View File

@@ -0,0 +1 @@
`db:"{{.field}}"`

View File

@@ -0,0 +1,15 @@
type (
{{.lowerStartCamelObject}}Model interface{
{{.method}}
}
default{{.upperStartCamelObject}}Model struct {
{{if .withCache}}sqlc.CachedConn{{else}}conn sqlx.SqlConn{{end}}
table string
}
{{.upperStartCamelObject}} struct {
{{.fields}}
}
)

View File

@@ -0,0 +1,286 @@
func (m *default{{.upperStartCamelObject}}Model) Update(ctx context.Context,session sqlx.Session, {{if .containsIndexCache}}newData{{else}}data{{end}} *{{.upperStartCamelObject}}) (sql.Result,error) {
{{if .withCache}}{{if .containsIndexCache}}data, err:=m.FindOne(ctx, newData.{{.upperStartCamelPrimaryKey}})
if err!=nil{
return nil,err
}
{{end}}{{.keys}}
return 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)
if session != nil{
return session.ExecCtx(ctx,query, {{.expressionValues}})
}
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)
if session != nil{
return session.ExecCtx(ctx,query, {{.expressionValues}})
}
return m.conn.ExecCtx(ctx, query, {{.expressionValues}}){{end}}
}
func (m *default{{.upperStartCamelObject}}Model) UpdateWithVersion(ctx context.Context,session sqlx.Session,{{if .containsIndexCache}}newData{{else}}data{{end}} *{{.upperStartCamelObject}}) error {
{{if .containsIndexCache}}
oldVersion := newData.Version
newData.Version += 1
{{else}}
oldVersion := data.Version
data.Version += 1
{{end}}
var sqlResult sql.Result
var err error
{{if .withCache}}{{if .containsIndexCache}}data, err:=m.FindOne(ctx, newData.{{.upperStartCamelPrimaryKey}})
if err!=nil{
return err
}
{{end}}{{.keys}}
sqlResult,err = 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}} and version = ? ", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder)
if session != nil{
return session.ExecCtx(ctx,query, {{.expressionValues}},oldVersion)
}
return conn.ExecCtx(ctx,query, {{.expressionValues}},oldVersion)
}, {{.keyValues}}){{else}}query := fmt.Sprintf("update %s set %s where {{.originalPrimaryKey}} = {{if .postgreSql}}$1{{else}}?{{end}} and version = ? ", m.table, {{.lowerStartCamelObject}}RowsWithPlaceHolder)
if session != nil{
sqlResult,err = session.ExecCtx(ctx,query, {{.expressionValues}},oldVersion)
}else{
sqlResult,err = m.conn.ExecCtx(ctx,query, {{.expressionValues}},oldVersion)
}
{{end}}
if err != nil {
return err
}
updateCount , err := sqlResult.RowsAffected()
if err != nil{
return err
}
if updateCount == 0 {
return ErrNoRowsUpdate
}
return nil
}
func (m *default{{.upperStartCamelObject}}Model) DeleteSoft(ctx context.Context,session sqlx.Session,data *{{.upperStartCamelObject}}) error {
data.DelState = globalkey.DelStateYes
data.DeleteTime = sql.NullTime{Time: time.Now(), Valid: true}
if err:= m.UpdateWithVersion(ctx,session, data);err!= nil{
return errors.Wrapf(errors.New("delete soft failed "),"{{.upperStartCamelObject}}Model delete err : %+v",err)
}
return nil
}
func (m *default{{.upperStartCamelObject}}Model) FindSum(ctx context.Context,builder squirrel.SelectBuilder, field string) (float64,error) {
if len(field) == 0 {
return 0, errors.Wrapf(errors.New("FindSum Least One Field"), "FindSum Least One Field")
}
builder = builder.Columns("IFNULL(SUM(" + field + "),0)")
query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).ToSql()
if err != nil {
return 0, err
}
var resp float64
{{if .withCache}}err = m.QueryRowNoCacheCtx(ctx,&resp, query, values...){{else}}
err = m.conn.QueryRowCtx(ctx,&resp, query, values...)
{{end}}
switch err {
case nil:
return resp, nil
default:
return 0, err
}
}
func (m *default{{.upperStartCamelObject}}Model) FindCount(ctx context.Context, builder squirrel.SelectBuilder, field string) (int64,error) {
if len(field) == 0 {
return 0, errors.Wrapf(errors.New("FindCount Least One Field"), "FindCount Least One Field")
}
builder = builder.Columns("COUNT(" + field + ")")
query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).ToSql()
if err != nil {
return 0, err
}
var resp int64
{{if .withCache}}err = m.QueryRowNoCacheCtx(ctx,&resp, query, values...){{else}}
err = m.conn.QueryRowCtx(ctx,&resp, query, values...)
{{end}}
switch err {
case nil:
return resp, nil
default:
return 0, err
}
}
func (m *default{{.upperStartCamelObject}}Model) FindAll(ctx context.Context,builder squirrel.SelectBuilder,orderBy string) ([]*{{.upperStartCamelObject}},error) {
builder = builder.Columns({{.lowerStartCamelObject}}Rows)
if orderBy == ""{
builder = builder.OrderBy("id DESC")
}else{
builder = builder.OrderBy(orderBy)
}
query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).ToSql()
if err != nil {
return nil, err
}
var resp []*{{.upperStartCamelObject}}
{{if .withCache}}err = m.QueryRowsNoCacheCtx(ctx,&resp, query, values...){{else}}
err = m.conn.QueryRowsCtx(ctx,&resp, query, values...)
{{end}}
switch err {
case nil:
return resp, nil
default:
return nil, err
}
}
func (m *default{{.upperStartCamelObject}}Model) FindPageListByPage(ctx context.Context,builder squirrel.SelectBuilder,page ,pageSize int64,orderBy string) ([]*{{.upperStartCamelObject}},error) {
builder = builder.Columns({{.lowerStartCamelObject}}Rows)
if orderBy == ""{
builder = builder.OrderBy("id DESC")
}else{
builder = builder.OrderBy(orderBy)
}
if page < 1{
page = 1
}
offset := (page - 1) * pageSize
query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).Offset(uint64(offset)).Limit(uint64(pageSize)).ToSql()
if err != nil {
return nil, err
}
var resp []*{{.upperStartCamelObject}}
{{if .withCache}}err = m.QueryRowsNoCacheCtx(ctx,&resp, query, values...){{else}}
err = m.conn.QueryRowsCtx(ctx,&resp, query, values...)
{{end}}
switch err {
case nil:
return resp, nil
default:
return nil, err
}
}
func (m *default{{.upperStartCamelObject}}Model) FindPageListByPageWithTotal(ctx context.Context,builder squirrel.SelectBuilder,page ,pageSize int64,orderBy string) ([]*{{.upperStartCamelObject}},int64,error) {
total, err := m.FindCount(ctx, builder, "id")
if err != nil {
return nil, 0, err
}
builder = builder.Columns({{.lowerStartCamelObject}}Rows)
if orderBy == ""{
builder = builder.OrderBy("id DESC")
}else{
builder = builder.OrderBy(orderBy)
}
if page < 1{
page = 1
}
offset := (page - 1) * pageSize
query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).Offset(uint64(offset)).Limit(uint64(pageSize)).ToSql()
if err != nil {
return nil,total, err
}
var resp []*{{.upperStartCamelObject}}
{{if .withCache}}err = m.QueryRowsNoCacheCtx(ctx,&resp, query, values...){{else}}
err = m.conn.QueryRowsCtx(ctx,&resp, query, values...)
{{end}}
switch err {
case nil:
return resp,total, nil
default:
return nil,total, err
}
}
func (m *default{{.upperStartCamelObject}}Model) FindPageListByIdDESC(ctx context.Context,builder squirrel.SelectBuilder ,preMinId ,pageSize int64) ([]*{{.upperStartCamelObject}},error) {
builder = builder.Columns({{.lowerStartCamelObject}}Rows)
if preMinId > 0 {
builder = builder.Where(" id < ? " , preMinId)
}
query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).OrderBy("id DESC").Limit(uint64(pageSize)).ToSql()
if err != nil {
return nil, err
}
var resp []*{{.upperStartCamelObject}}
{{if .withCache}}err = m.QueryRowsNoCacheCtx(ctx,&resp, query, values...){{else}}
err = m.conn.QueryRowsCtx(ctx,&resp, query, values...)
{{end}}
switch err {
case nil:
return resp, nil
default:
return nil, err
}
}
func (m *default{{.upperStartCamelObject}}Model) FindPageListByIdASC(ctx context.Context,builder squirrel.SelectBuilder,preMaxId ,pageSize int64) ([]*{{.upperStartCamelObject}},error) {
builder = builder.Columns({{.lowerStartCamelObject}}Rows)
if preMaxId > 0 {
builder = builder.Where(" id > ? " , preMaxId)
}
query, values, err := builder.Where("del_state = ?", globalkey.DelStateNo).OrderBy("id ASC").Limit(uint64(pageSize)).ToSql()
if err != nil {
return nil, err
}
var resp []*{{.upperStartCamelObject}}
{{if .withCache}}err = m.QueryRowsNoCacheCtx(ctx,&resp, query, values...){{else}}
err = m.conn.QueryRowsCtx(ctx,&resp, query, values...)
{{end}}
switch err {
case nil:
return resp, nil
default:
return nil, err
}
}
func (m *default{{.upperStartCamelObject}}Model) Trans(ctx context.Context,fn func(ctx context.Context,session sqlx.Session) error) error {
{{if .withCache}}
return m.TransactCtx(ctx,func(ctx context.Context,session sqlx.Session) error {
return fn(ctx,session)
})
{{else}}
return m.conn.TransactCtx(ctx,func(ctx context.Context,session sqlx.Session) error {
return fn(ctx,session)
})
{{end}}
}
func(m *default{{.upperStartCamelObject}}Model) SelectBuilder() squirrel.SelectBuilder {
return squirrel.Select().From(m.table)
}

View File

@@ -0,0 +1,9 @@
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}} "create_time", "update_time"), ","){{else}}strings.Join(stringx.Remove({{.lowerStartCamelObject}}FieldNames, {{if .autoIncrement}}"{{.originalPrimaryKey}}",{{end}} "`create_time`", "`update_time`"), ","){{end}}
{{.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}}
{{if .withCache}}{{.cacheKeys}}{{end}}
)

View File

@@ -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")
)

View File

@@ -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
}

View File

@@ -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}}

View File

@@ -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"`
}

View File

@@ -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)
}

View File

@@ -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}}

View File

@@ -0,0 +1,7 @@
package config
import "github.com/zeromicro/go-zero/zrpc"
type Config struct {
zrpc.RpcServerConf
}

View File

@@ -0,0 +1,6 @@
Name: {{.serviceName}}.rpc
ListenOn: 0.0.0.0:8080
Etcd:
Hosts:
- 127.0.0.1:2379
Key: {{.serviceName}}.rpc

View File

@@ -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
}

View File

@@ -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}}

View File

@@ -0,0 +1,42 @@
package main
import (
"flag"
"fmt"
{{.imports}}
"hm-server/common/interceptor/rpcserver"
"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)
}
})
//rpc log
s.AddUnaryInterceptors(rpcserver.LoggerInterceptor)
defer s.Stop()
fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
s.Start()
}

View File

@@ -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}})
}

View File

@@ -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}}

View File

@@ -0,0 +1,13 @@
package svc
import {{.imports}}
type ServiceContext struct {
Config config.Config
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config:c,
}
}

View File

@@ -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);
}