diff --git a/config.yaml.example b/config.yaml.example index 863f229..7d7d6a1 100644 --- a/config.yaml.example +++ b/config.yaml.example @@ -1,6 +1,9 @@ app: - jwt_secret: '23347$040412' + jwt_secret: 'viletyy + jwt_issuer: 'potato' + jwt_expire: '7200' run_mode: 'debug' + page_size: 10 server: http_port: 8000 read_timeout: 60 diff --git a/config/app.go b/config/app.go index 46239ad..3e99f32 100644 --- a/config/app.go +++ b/config/app.go @@ -1,13 +1,15 @@ /* * @Date: 2021-03-22 09:46:19 * @LastEditors: viletyy - * @LastEditTime: 2021-03-22 17:14:02 + * @LastEditTime: 2021-06-10 18:24:42 * @FilePath: /potato/config/app.go */ package config type App struct { - PageSize int64 `mapstructure:"page_size" json:"page_size" yaml:"page_size"` - JwtSecret string `mapstructure:"jwt_secret" json:"jwt_secret" yaml:"jwt_secret"` - RunMode string `mapstructure:"run_mode" json:"run_mode" yaml:"run_mode"` + PageSize int64 `mapstructure:"page_size" json:"page_size" yaml:"page_size"` + JwtSecret string `mapstructure:"jwt_secret" json:"jwt_secret" yaml:"jwt_secret"` + JwtIssuser string `mapstructure:"jwt_issuser" json:"jwt_issuser" yaml:"jwt_issuser"` + JwtExpire int64 `mapstructure:"jwt_expire" json:"jwt_expire" yaml:"jwt_expire"` + RunMode string `mapstructure:"run_mode" json:"run_mode" yaml:"run_mode"` } diff --git a/docs/docs.go b/docs/docs.go index bd61d4e..09480f7 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -105,8 +105,9 @@ var doc = `{ "required": true }, { + "maxLength": 100, "type": "string", - "description": "系统厂商名称", + "description": "名称", "name": "name", "in": "query" }, @@ -125,9 +126,21 @@ var doc = `{ ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"获取成功\"}", + "description": "请求成功", "schema": { - "type": "string" + "$ref": "#/definitions/errcode.Error" + } + }, + "400": { + "description": "请求错误", + "schema": { + "$ref": "#/definitions/errcode.Error" + } + }, + "500": { + "description": "内部错误", + "schema": { + "$ref": "#/definitions/errcode.Error" } } } @@ -150,22 +163,25 @@ var doc = `{ "name": "Authorization", "in": "header", "required": true - }, - { - "description": "Vendor模型", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/basic.CreateVendorRequest" - } } ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"创建成功\"}", + "description": "请求成功", "schema": { - "type": "string" + "$ref": "#/definitions/errcode.Error" + } + }, + "400": { + "description": "请求错误", + "schema": { + "$ref": "#/definitions/errcode.Error" + } + }, + "500": { + "description": "内部错误", + "schema": { + "$ref": "#/definitions/errcode.Error" } } } @@ -201,9 +217,21 @@ var doc = `{ ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"删除成功\"}", + "description": "请求成功", "schema": { - "type": "string" + "$ref": "#/definitions/errcode.Error" + } + }, + "400": { + "description": "请求错误", + "schema": { + "$ref": "#/definitions/errcode.Error" + } + }, + "500": { + "description": "内部错误", + "schema": { + "$ref": "#/definitions/errcode.Error" } } } @@ -233,22 +261,25 @@ var doc = `{ "name": "id", "in": "path", "required": true - }, - { - "description": "Vendor模型", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/basic.UpdateVendorRequest" - } } ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"更新成功\"}", + "description": "请求成功", "schema": { - "type": "string" + "$ref": "#/definitions/errcode.Error" + } + }, + "400": { + "description": "请求错误", + "schema": { + "$ref": "#/definitions/errcode.Error" + } + }, + "500": { + "description": "内部错误", + "schema": { + "$ref": "#/definitions/errcode.Error" } } } @@ -256,28 +287,17 @@ var doc = `{ } }, "definitions": { - "basic.CreateVendorRequest": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "uuid": { - "type": "integer" - } - } - }, - "basic.UpdateVendorRequest": { + "errcode.Error": { "type": "object", "properties": { - "name": { - "type": "string" - }, - "uuid": { + "code": { "type": "integer" + }, + "data": { + "type": "object" + }, + "msg": { + "type": "string" } } }, @@ -333,7 +353,7 @@ var SwaggerInfo = swaggerInfo{ BasePath: "/api", Schemes: []string{}, Title: "Potato Api", - Description: "This is a data_govern use golang", + Description: "This is a potato use golang", } type s struct{} diff --git a/docs/swagger.json b/docs/swagger.json index e58d692..efdd5d0 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -1,7 +1,7 @@ { "swagger": "2.0", "info": { - "description": "This is a data_govern use golang", + "description": "This is a potato use golang", "title": "Potato Api", "contact": {}, "version": "1.0" @@ -89,8 +89,9 @@ "required": true }, { + "maxLength": 100, "type": "string", - "description": "系统厂商名称", + "description": "名称", "name": "name", "in": "query" }, @@ -109,9 +110,21 @@ ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"获取成功\"}", + "description": "请求成功", "schema": { - "type": "string" + "$ref": "#/definitions/errcode.Error" + } + }, + "400": { + "description": "请求错误", + "schema": { + "$ref": "#/definitions/errcode.Error" + } + }, + "500": { + "description": "内部错误", + "schema": { + "$ref": "#/definitions/errcode.Error" } } } @@ -134,22 +147,25 @@ "name": "Authorization", "in": "header", "required": true - }, - { - "description": "Vendor模型", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/basic.CreateVendorRequest" - } } ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"创建成功\"}", + "description": "请求成功", "schema": { - "type": "string" + "$ref": "#/definitions/errcode.Error" + } + }, + "400": { + "description": "请求错误", + "schema": { + "$ref": "#/definitions/errcode.Error" + } + }, + "500": { + "description": "内部错误", + "schema": { + "$ref": "#/definitions/errcode.Error" } } } @@ -185,9 +201,21 @@ ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"删除成功\"}", + "description": "请求成功", "schema": { - "type": "string" + "$ref": "#/definitions/errcode.Error" + } + }, + "400": { + "description": "请求错误", + "schema": { + "$ref": "#/definitions/errcode.Error" + } + }, + "500": { + "description": "内部错误", + "schema": { + "$ref": "#/definitions/errcode.Error" } } } @@ -217,22 +245,25 @@ "name": "id", "in": "path", "required": true - }, - { - "description": "Vendor模型", - "name": "data", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/basic.UpdateVendorRequest" - } } ], "responses": { "200": { - "description": "{\"success\":true,\"data\":{},\"msg\":\"更新成功\"}", + "description": "请求成功", "schema": { - "type": "string" + "$ref": "#/definitions/errcode.Error" + } + }, + "400": { + "description": "请求错误", + "schema": { + "$ref": "#/definitions/errcode.Error" + } + }, + "500": { + "description": "内部错误", + "schema": { + "$ref": "#/definitions/errcode.Error" } } } @@ -240,28 +271,17 @@ } }, "definitions": { - "basic.CreateVendorRequest": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "uuid": { - "type": "integer" - } - } - }, - "basic.UpdateVendorRequest": { + "errcode.Error": { "type": "object", "properties": { - "name": { - "type": "string" - }, - "uuid": { + "code": { "type": "integer" + }, + "data": { + "type": "object" + }, + "msg": { + "type": "string" } } }, diff --git a/docs/swagger.yaml b/docs/swagger.yaml index f59589b..6caefe9 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1,20 +1,13 @@ basePath: /api definitions: - basic.CreateVendorRequest: + errcode.Error: properties: - name: - type: string - uuid: + code: type: integer - required: - - name - type: object - basic.UpdateVendorRequest: - properties: - name: + data: + type: object + msg: type: string - uuid: - type: integer type: object v1.AuthRequest: properties: @@ -40,7 +33,7 @@ definitions: type: object info: contact: {} - description: This is a data_govern use golang + description: This is a potato use golang title: Potato Api version: "1.0" paths: @@ -92,8 +85,9 @@ paths: name: Authorization required: true type: string - - description: 系统厂商名称 + - description: 名称 in: query + maxLength: 100 name: name type: string - description: 页码 @@ -108,9 +102,17 @@ paths: - application/json responses: "200": - description: '{"success":true,"data":{},"msg":"获取成功"}' + description: 请求成功 schema: - type: string + $ref: '#/definitions/errcode.Error' + "400": + description: 请求错误 + schema: + $ref: '#/definitions/errcode.Error' + "500": + description: 内部错误 + schema: + $ref: '#/definitions/errcode.Error' summary: 系统厂商列表 tags: - vendors @@ -123,19 +125,21 @@ paths: name: Authorization required: true type: string - - description: Vendor模型 - in: body - name: data - required: true - schema: - $ref: '#/definitions/basic.CreateVendorRequest' produces: - application/json responses: "200": - description: '{"success":true,"data":{},"msg":"创建成功"}' + description: 请求成功 schema: - type: string + $ref: '#/definitions/errcode.Error' + "400": + description: 请求错误 + schema: + $ref: '#/definitions/errcode.Error' + "500": + description: 内部错误 + schema: + $ref: '#/definitions/errcode.Error' summary: 新增系统厂商 tags: - vendors @@ -158,9 +162,17 @@ paths: - application/json responses: "200": - description: '{"success":true,"data":{},"msg":"删除成功"}' + description: 请求成功 schema: - type: string + $ref: '#/definitions/errcode.Error' + "400": + description: 请求错误 + schema: + $ref: '#/definitions/errcode.Error' + "500": + description: 内部错误 + schema: + $ref: '#/definitions/errcode.Error' summary: 删除系统厂商 tags: - vendors @@ -178,19 +190,21 @@ paths: name: id required: true type: integer - - description: Vendor模型 - in: body - name: data - required: true - schema: - $ref: '#/definitions/basic.UpdateVendorRequest' produces: - application/json responses: "200": - description: '{"success":true,"data":{},"msg":"更新成功"}' + description: 请求成功 schema: - type: string + $ref: '#/definitions/errcode.Error' + "400": + description: 请求错误 + schema: + $ref: '#/definitions/errcode.Error' + "500": + description: 内部错误 + schema: + $ref: '#/definitions/errcode.Error' summary: 修改系统厂商 tags: - vendors diff --git a/initialize/gorm.go b/initialize/gorm.go index face8c3..634964f 100644 --- a/initialize/gorm.go +++ b/initialize/gorm.go @@ -1,7 +1,7 @@ /* * @Date: 2021-03-22 10:12:38 * @LastEditors: viletyy - * @LastEditTime: 2021-06-10 15:43:12 + * @LastEditTime: 2021-06-10 17:52:06 * @FilePath: /potato/initialize/gorm.go */ package initialize @@ -60,8 +60,6 @@ func GormSet(db *gorm.DB) { // 设置迁移 db.AutoMigrate( basic.Vendor{}, - basic.Business{}, - basic.MetaDatabase{}, model.User{}, ) diff --git a/internal/controller/api/v1/auth.go b/internal/controller/api/v1/auth.go new file mode 100644 index 0000000..aaf74d4 --- /dev/null +++ b/internal/controller/api/v1/auth.go @@ -0,0 +1,15 @@ +/* + * @Date: 2021-06-10 18:58:25 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 19:02:14 + * @FilePath: /potato/internal/controller/api/v1/auth.go + */ +package v1 + +import ( + "github.com/gin-gonic/gin" +) + +func GetAuth(c *gin.Context) { + +} diff --git a/internal/controller/api/v1/basic/vendor.go b/internal/controller/api/v1/basic/vendor.go index 3c0b9d9..dcf23fa 100644 --- a/internal/controller/api/v1/basic/vendor.go +++ b/internal/controller/api/v1/basic/vendor.go @@ -1,25 +1,16 @@ +/* + * @Date: 2021-03-21 19:54:57 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 17:56:42 + * @FilePath: /potato/internal/controller/api/v1/basic/vendor.go + */ package basic import ( - "net/http" - "github.com/gin-gonic/gin" - "github.com/go-playground/validator/v10" - "github.com/viletyy/potato/global" - "github.com/viletyy/potato/internal/model/basic" - "github.com/viletyy/potato/pkg" - "go.uber.org/zap" ) -type CreateVendorRequest struct { - Name string `json:"name" validate:"required"` - Uuid int `json:"uuid"` -} - -type UpdateVendorRequest struct { - Name string `json:"name"` - Uuid int `json:"uuid"` -} +type Vendor struct{} // @Summary 系统厂商列表 // @Tags vendors @@ -27,24 +18,12 @@ type UpdateVendorRequest struct { // @Accept json // @Produce json // @Param Authorization header string true "auth by /auth" -// @Param name query string false "系统厂商名称" +// @Param name query string false "名称" maxlength(100) // @Param page query int false "页码" // @Param page_size query int false "每页数量" -// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}" +// @Success 200 {object} basic.Vendor "请求成功" // @Router /v1/vendors [get] -func GetVendors(c *gin.Context) { - var search basic.VendorSearch - - search.Name = c.Query("name") - search.Page, search.PageSize = pkg.GetPageInfo(c) - - if result, err := basic.GetVendors(&search); err != nil { - global.GO_LOG.Error("获取失败!", zap.Any("err", err)) - pkg.FailWithMessage("获取失败", c) - } else { - pkg.OkWithDetailed(result, "获取成功", c) - } -} +func (vendor Vendor) List(c *gin.Context) {} // @Summary 新增系统厂商 // @Tags vendors @@ -52,43 +31,9 @@ func GetVendors(c *gin.Context) { // @Accept mpfd // @Produce json // @Param Authorization header string true "auth by /auth" -// @Param data body CreateVendorRequest true "Vendor模型" -// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}" +// @Success 200 {object} basic.Vendor "请求成功" // @Router /v1/vendors [post] -func CreateVendor(c *gin.Context) { - var vendor CreateVendorRequest - if err := c.ShouldBindJSON(&vendor); err != nil { - if errs, ok := err.(validator.ValidationErrors); !ok { - c.JSON(http.StatusBadRequest, gin.H{ - "msg": err.Error(), - }) - return - } else { - c.JSON(http.StatusBadRequest, gin.H{ - "msg": errs.Translate(pkg.Trans), - }) - return - } - } - - if exist := basic.ExistVendorByName(vendor.Name); exist { - global.GO_LOG.Error("该系统厂商名称已存在!") - pkg.FailWithMessage("该系统厂商名称已存在", c) - return - } - if exist := basic.ExistVendorByUuid(vendor.Uuid); exist { - global.GO_LOG.Error("该系统厂商uuid已存在!") - pkg.FailWithMessage("该系统厂商uuid已存在", c) - return - } - - if mVendor, err := basic.CreateVendor(basic.Vendor{Name: vendor.Name, Uuid: vendor.Uuid}); err != nil { - global.GO_LOG.Error("创建失败!", zap.Any("err", err)) - pkg.FailWithMessage("创建失败", c) - } else { - pkg.OkWithDetailed(mVendor, "创建成功", c) - } -} +func (vendor Vendor) Create(c *gin.Context) {} // @Summary 修改系统厂商 // @Tags vendors @@ -97,49 +42,9 @@ func CreateVendor(c *gin.Context) { // @Produce json // @Param Authorization header string true "auth by /auth" // @Param id path int true "系统厂商 ID" -// @Param data body UpdateVendorRequest true "Vendor模型" -// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}" +// @Success 200 {object} basic.Vendor "请求成功" // @Router /v1/vendors/{id} [patch] -func UpdateVendor(c *gin.Context) { - vendor, gErr := basic.GetVendorById(c.Param("id")) - if gErr != nil { - global.GO_LOG.Error("系统厂商不存在!", zap.Any("err", gErr)) - pkg.FailWithMessage("系统厂商不存在!", c) - return - } - - if err := c.ShouldBindJSON(&vendor); err != nil { - if errs, ok := err.(validator.ValidationErrors); !ok { - c.JSON(http.StatusBadRequest, gin.H{ - "msg": err.Error(), - }) - return - } else { - c.JSON(http.StatusBadRequest, gin.H{ - "msg": errs.Translate(pkg.Trans), - }) - return - } - } - - if exist := basic.ExistVendorByName(vendor.Name); exist { - global.GO_LOG.Error("该系统厂商名称已存在!") - pkg.FailWithMessage("该系统厂商名称已存在", c) - return - } - if exist := basic.ExistVendorByUuid(vendor.Uuid); exist { - global.GO_LOG.Error("该系统厂商uuid已存在!") - pkg.FailWithMessage("该系统厂商uuid已存在", c) - return - } - - if err := basic.UpdateVendor(&vendor); err != nil { - global.GO_LOG.Error("更新失败!", zap.Any("err", err)) - pkg.FailWithMessage("更新失败", c) - } else { - pkg.OkWithDetailed(vendor, "更新成功", c) - } -} +func (vendor Vendor) Update(c *gin.Context) {} // @Summary 删除系统厂商 // @Tags vendors @@ -148,19 +53,7 @@ func UpdateVendor(c *gin.Context) { // @Produce json // @Param Authorization header string true "auth by /auth" // @Param id path int true "系统厂商 ID" -// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}" +// @Success 200 {object} basic.Vendor "请求成功" // @Router /v1/vendors/{id} [delete] -func DeleteVendor(c *gin.Context) { - vendor, gErr := basic.GetVendorById(c.Param("id")) - if gErr != nil { - global.GO_LOG.Error("系统厂商不存在!", zap.Any("err", gErr)) - pkg.FailWithMessage("系统厂商不存在!", c) - return - } - if err := basic.DeleteVendor(&vendor); err != nil { - global.GO_LOG.Error("删除失败!", zap.Any("err", err)) - pkg.FailWithMessage("删除失败", c) - } else { - pkg.OkWithMessage("删除成功", c) - } +func (vendor Vendor) Delete(c *gin.Context) { } diff --git a/internal/controller/api/v1/user.go b/internal/controller/api/v1/user.go index 8023a3f..07c6d4e 100644 --- a/internal/controller/api/v1/user.go +++ b/internal/controller/api/v1/user.go @@ -1,122 +1,7 @@ /* * @Date: 2021-03-21 19:54:57 * @LastEditors: viletyy - * @LastEditTime: 2021-06-10 15:23:41 + * @LastEditTime: 2021-06-10 19:02:24 * @FilePath: /potato/internal/controller/api/v1/user.go */ package v1 - -import ( - "net/http" - - "github.com/gin-gonic/gin" - "github.com/go-playground/validator/v10" - "github.com/viletyy/potato/global" - "github.com/viletyy/potato/internal/model" - "github.com/viletyy/potato/pkg" - "github.com/viletyy/yolk/crypt" - "go.uber.org/zap" -) - -type AuthResponse struct { - User model.User `json:"user"` - Token string `json:"token"` -} - -type AuthRequest struct { - Username string `json:"username" validate:"required"` - Password string `json:"password" validate:"required,gte=6"` -} - -type RegisterRequest struct { - Username string `json:"username" validate:"required"` - Password string `json:"password" validate:"required,gte=6"` - Nickname string `json:"nickname"` -} - -// @Summary 用户验证 -// @Description -// @Accept json -// @Produce json -// @Param data body AuthRequest true "用户名,密码" -// @Success 200 {string} json "{"code" : 200, "data" : {"token" : ""}, "msg" : "ok"}" -// @Router /v1/auth [post] -func Auth(c *gin.Context) { - var user AuthRequest - if err := c.ShouldBindJSON(&user); err != nil { - if errs, ok := err.(validator.ValidationErrors); !ok { - c.JSON(http.StatusBadRequest, gin.H{ - "msg": err.Error(), - }) - return - } else { - c.JSON(http.StatusBadRequest, gin.H{ - "msg": errs.Translate(pkg.Trans), - }) - return - } - } - - mUser, gErr := model.GetUserByUsername(user.Username) - if gErr != nil { - global.GO_LOG.Error("查找用户失败", zap.Any("err", gErr)) - pkg.FailWithMessage("查找用户失败", c) - return - } - - isTrue := mUser.CheckPassword(user.Password) - if !isTrue { - global.GO_LOG.Error("用户密码不正确") - pkg.FailWithMessage("用户密码不正确", c) - return - } - - token, tokenErr := pkg.GenerateToken(mUser.ID) - if tokenErr != nil { - global.GO_LOG.Error("获取token失败", zap.Any("err", tokenErr)) - pkg.FailWithMessage("获取token失败", c) - return - } - - pkg.OkWithDetailed(AuthResponse{ - User: mUser, - Token: token, - }, "登录成功", c) -} - -// @Summary 注册用户 -// @Description -// @Accept json -// @Produce json -// @Param data body RegisterRequest true "用户名" -// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}" -// @Router /v1/register [post] -func Register(c *gin.Context) { - var user RegisterRequest - if err := c.ShouldBindJSON(&user); err != nil { - if errs, ok := err.(validator.ValidationErrors); !ok { - c.JSON(http.StatusBadRequest, gin.H{ - "msg": err.Error(), - }) - return - } else { - c.JSON(http.StatusBadRequest, gin.H{ - "msg": errs.Translate(pkg.Trans), - }) - return - } - } - - if isExsit := model.ExistUserByUsername(user.Username); isExsit { - global.GO_LOG.Error("用户已存在") - pkg.FailWithMessage("用户已存在", c) - return - } - - if err := model.CreateUser(model.User{Username: user.Username, Password: crypt.Md5Encode(user.Password), Nickname: user.Nickname}); err != nil { - global.GO_LOG.Error("创建失败!", zap.Any("err", err)) - pkg.FailWithMessage("创建失败", c) - } else { - pkg.OkWithMessage("创建成功", c) - } -} diff --git a/internal/dao/auth.go b/internal/dao/auth.go new file mode 100644 index 0000000..ce829aa --- /dev/null +++ b/internal/dao/auth.go @@ -0,0 +1,15 @@ +/* + * @Date: 2021-06-10 18:54:19 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 18:55:32 + * @FilePath: /potato/internal/dao/auth.go + */ +package dao + +import "github.com/viletyy/potato/internal/model" + +func (d *Dao) GetAuth(appKey, appSecret string) (model.Auth, error) { + auth := model.Auth{AppKey: appKey, AppSecret: appSecret} + + return auth.Get(d.Engine) +} diff --git a/internal/dao/dao.go b/internal/dao/dao.go new file mode 100644 index 0000000..763c722 --- /dev/null +++ b/internal/dao/dao.go @@ -0,0 +1,17 @@ +/* + * @Date: 2021-06-10 18:46:10 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 18:48:41 + * @FilePath: /potato/internal/dao/auth.go + */ +package dao + +import "github.com/jinzhu/gorm" + +type Dao struct { + Engine *gorm.DB +} + +func New(engine *gorm.DB) *Dao { + return &Dao{Engine: engine} +} diff --git a/internal/middleware/translations.go b/internal/middleware/translations.go new file mode 100644 index 0000000..79ba286 --- /dev/null +++ b/internal/middleware/translations.go @@ -0,0 +1,45 @@ +/* + * @Date: 2021-06-10 18:02:35 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 18:19:12 + * @FilePath: /potato/internal/middleware/translations.go + */ +package middleware + +import ( + "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/binding" + "github.com/go-playground/locales/en" + "github.com/go-playground/locales/zh" + "github.com/go-playground/validator/v10" + + ut "github.com/go-playground/universal-translator" + enTranslations "github.com/go-playground/validator/v10/translations/en" + zhTranslations "github.com/go-playground/validator/v10/translations/zh" +) + +func Translations() gin.HandlerFunc { + return func(c *gin.Context) { + uni := ut.New(en.New(), zh.New()) + locale := c.GetHeader("locale") + trans, _ := uni.GetTranslator(locale) + v, ok := binding.Validator.Engine().(*validator.Validate) + v.SetTagName("validate") + if ok { + switch locale { + case "zh": + _ = zhTranslations.RegisterDefaultTranslations(v, trans) + break + case "en": + _ = enTranslations.RegisterDefaultTranslations(v, trans) + break + default: + _ = zhTranslations.RegisterDefaultTranslations(v, trans) + break + } + c.Set("trans", trans) + } + + c.Next() + } +} diff --git a/internal/model/auth.go b/internal/model/auth.go new file mode 100644 index 0000000..733dad8 --- /dev/null +++ b/internal/model/auth.go @@ -0,0 +1,26 @@ +/* + * @Date: 2021-06-10 18:21:37 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 18:45:57 + * @FilePath: /potato/internal/model/auth.go + */ +package model + +import "github.com/jinzhu/gorm" + +type Auth struct { + Model + AppKey string `json:"app_key"` + AppSecret string `json:"app_secret"` +} + +func (a Auth) Get(db *gorm.DB) (Auth, error) { + var auth Auth + db = db.Where("app_key = ? AND app_secret = ? AND deleted_at = ?", a.AppKey, a.AppSecret, nil) + err := db.First(&auth).Error + if err != nil && err != gorm.ErrRecordNotFound { + return auth, err + } + + return auth, nil +} diff --git a/internal/model/basic/business.go b/internal/model/basic/business.go deleted file mode 100644 index 058e97a..0000000 --- a/internal/model/basic/business.go +++ /dev/null @@ -1,97 +0,0 @@ -/* - * @Date: 2021-03-21 19:54:57 - * @LastEditors: viletyy - * @LastEditTime: 2021-06-10 15:26:12 - * @FilePath: /potato/internal/model/basic/business.go - */ -package basic - -import ( - "github.com/viletyy/potato/global" - "github.com/viletyy/potato/internal/model" - "github.com/viletyy/potato/pkg" -) - -type BusinessSearch struct { - Business - pkg.PageInfo -} - -type Business struct { - model.Model - - Name string `json:"name"` - Description string `json:"description"` - Uuid int `json:"uuid"` -} - -func GetBusinesses(search *BusinessSearch) (searchResult pkg.SearchResult, err error) { - var businesses []Business - offset := search.PageInfo.PageSize * (search.PageInfo.Page - 1) - limit := search.PageInfo.Page - db := global.GO_DB.Where(search.Business) - err = db.Count(&searchResult.Total).Error - if err != nil { - return - } - err = db.Offset(offset).Limit(limit).Find(&businesses).Error - if err != nil { - return - } - searchResult.Page = search.PageInfo.Page - searchResult.PageSize = search.PageInfo.PageSize - searchResult.List = businesses - return -} - -func GetBusinessById(id int) (business Business, err error) { - err = global.GO_DB.Where("id = ?", id).First(&business).Error - return -} - -func GetBusinessByName(name string) (business Business, err error) { - err = global.GO_DB.Where("name = ?", name).First(&business).Error - return -} - -func GetBusinessByUuid(uuid int64) (business Business, err error) { - err = global.GO_DB.Where("uuid = ?", uuid).First(&business).Error - return -} - -func ExistBusinessById(id int) bool { - var business Business - global.GO_DB.Where("id = ?", id).First(&business) - - return business.ID > 0 -} - -func ExistBusinessByName(name string) bool { - var business Business - global.GO_DB.Where("name = ?", name).First(&business) - - return business.ID > 0 -} - -func ExistBusinessByUuid(uuid int64) bool { - var business Business - global.GO_DB.Where("uuid = ?", uuid).First(&business) - - return business.ID > 0 -} - -func CreateBusiness(business Business) (err error) { - err = global.GO_DB.Create(&business).Error - - return err -} - -func UpdateBusiness(business *Business) (err error) { - err = global.GO_DB.Save(&business).Error - return -} - -func DeleteBusiness(business *Business) (err error) { - err = global.GO_DB.Delete(&business).Error - return -} diff --git a/internal/model/basic/meta_database.go b/internal/model/basic/meta_database.go deleted file mode 100644 index e297b2a..0000000 --- a/internal/model/basic/meta_database.go +++ /dev/null @@ -1,97 +0,0 @@ -/* - * @Date: 2021-03-21 19:54:57 - * @LastEditors: viletyy - * @LastEditTime: 2021-06-10 15:26:27 - * @FilePath: /potato/internal/model/basic/meta_database.go - */ -package basic - -import ( - "time" - - "github.com/viletyy/potato/global" - "github.com/viletyy/potato/internal/model" - "github.com/viletyy/potato/pkg" -) - -type MetaDatabaseSearch struct { - MetaDatabase - pkg.PageInfo -} - -type MetaDatabase struct { - model.Model - Name string `json:"name"` - Adapter string `json:"adapter"` - Host string `json:"host"` - Port string `json:"port"` - DbName string `json:"db_name"` - Username string `json:"username"` - Password string `json:"password"` - LastConnectTime time.Time `json:"last_connect_time"` - Usable bool `json:"usable"` - Comment string `json:"comment"` - VendorId int64 `json:"vendor_id"` - BusinessId int64 `json:"business_id"` - Vendor Vendor - Business Business -} - -func GetMetaDatabases(search *MetaDatabaseSearch) (searchResult pkg.SearchResult, err error) { - var metaDatabases []MetaDatabase - offset := search.PageInfo.PageSize * (search.PageInfo.Page - 1) - limit := search.PageInfo.Page - db := global.GO_DB.Where(search.MetaDatabase) - err = db.Count(&searchResult.Total).Error - if err != nil { - return - } - err = db.Offset(offset).Limit(limit).Find(&metaDatabases).Error - if err != nil { - return - } - searchResult.Page = search.PageInfo.Page - searchResult.PageSize = search.PageInfo.PageSize - searchResult.List = metaDatabases - return -} - -func GetMetaDatabaseById(id int) (metaDatabase MetaDatabase, err error) { - err = global.GO_DB.Where("id = ?", id).First(&metaDatabase).Error - return -} - -func GetMetaDatabaseByName(name string) (metaDatabase MetaDatabase, err error) { - err = global.GO_DB.Where("name = ?", name).First(&metaDatabase).Error - return -} - -func ExistMetaDatabaseById(id int) bool { - var metaDatabase MetaDatabase - global.GO_DB.Where("id = ?", id).First(&metaDatabase) - - return metaDatabase.ID > 0 -} - -func ExistMetaDatabaseByName(name string) bool { - var metaDatabase MetaDatabase - global.GO_DB.Where("name = ?", name).First(&metaDatabase) - - return metaDatabase.ID > 0 -} - -func CreateMetaDatabase(metaDatabase MetaDatabase) (err error) { - err = global.GO_DB.Create(&metaDatabase).Error - - return err -} - -func UpdateMetaDatabase(metaDatabase *MetaDatabase) (err error) { - err = global.GO_DB.Save(&metaDatabase).Error - return -} - -func DeleteMetaDatabase(metaDatabase *MetaDatabase) (err error) { - err = global.GO_DB.Delete(&metaDatabase).Error - return -} diff --git a/internal/model/basic/vendor.go b/internal/model/basic/vendor.go index 298d35d..1a279e7 100644 --- a/internal/model/basic/vendor.go +++ b/internal/model/basic/vendor.go @@ -1,96 +1,18 @@ /* * @Date: 2021-03-21 19:54:57 * @LastEditors: viletyy - * @LastEditTime: 2021-06-10 15:26:36 + * @LastEditTime: 2021-06-10 17:54:47 * @FilePath: /potato/internal/model/basic/vendor.go */ package basic import ( - "github.com/viletyy/potato/global" "github.com/viletyy/potato/internal/model" - "github.com/viletyy/potato/pkg" ) -type VendorSearch struct { - Vendor - pkg.PageInfo -} - type Vendor struct { model.Model Name string `json:"name"` Uuid int `json:"uuid"` } - -func GetVendors(search *VendorSearch) (searchResult pkg.SearchResult, err error) { - var vendors []Vendor - offset := search.PageInfo.PageSize * (search.PageInfo.Page - 1) - limit := search.PageInfo.PageSize - db := global.GO_DB.Model(&Vendor{}).Where(search.Vendor) - err = db.Count(&searchResult.Total).Error - if err != nil { - return - } - err = db.Offset(offset).Limit(limit).Find(&vendors).Error - if err != nil { - return - } - searchResult.Page = search.PageInfo.Page - searchResult.PageSize = search.PageInfo.PageSize - searchResult.List = vendors - return -} - -func GetVendorById(id interface{}) (vendor Vendor, err error) { - err = global.GO_DB.Where("id = ?", id).First(&vendor).Error - return -} - -func GetVendorByName(name string) (vendor Vendor, err error) { - err = global.GO_DB.Where("name = ?", name).First(&vendor).Error - return -} - -func GetVendorByUuid(uuid interface{}) (vendor Vendor, err error) { - err = global.GO_DB.Where("uuid = ?", uuid).First(&vendor).Error - return -} - -func ExistVendorById(id interface{}) bool { - var vendor Vendor - global.GO_DB.Where("id = ?", id).First(&vendor) - - return vendor.ID > 0 -} - -func ExistVendorByName(name string) bool { - var vendor Vendor - global.GO_DB.Where("name = ?", name).First(&vendor) - - return vendor.ID > 0 -} - -func ExistVendorByUuid(uuid interface{}) bool { - var vendor Vendor - global.GO_DB.Where("uuid = ?", uuid).First(&vendor) - - return vendor.ID > 0 -} - -func CreateVendor(vendor Vendor) (mVendor *Vendor, err error) { - err = global.GO_DB.Create(&vendor).Error - - return &vendor, err -} - -func UpdateVendor(vendor *Vendor) (err error) { - err = global.GO_DB.Save(&vendor).Error - return -} - -func DeleteVendor(vendor *Vendor) (err error) { - err = global.GO_DB.Delete(&vendor).Error - return -} diff --git a/internal/model/user.go b/internal/model/user.go index 7269e41..b0bef12 100644 --- a/internal/model/user.go +++ b/internal/model/user.go @@ -1,22 +1,11 @@ /* * @Date: 2021-03-21 19:54:57 * @LastEditors: viletyy - * @LastEditTime: 2021-06-10 15:26:49 + * @LastEditTime: 2021-06-10 18:20:33 * @FilePath: /potato/internal/model/user.go */ package model -import ( - "github.com/viletyy/potato/global" - "github.com/viletyy/potato/pkg" - "github.com/viletyy/yolk/crypt" -) - -type UserSearch struct { - User - pkg.PageInfo -} - type User struct { Model @@ -25,66 +14,3 @@ type User struct { Nickname string `json:"nickname"` IsAdmin bool `json:"is_admin" gorm:"default: false"` } - -func GetUsers(search *UserSearch) (searchResult pkg.SearchResult, err error) { - var users []User - offset := search.PageInfo.PageSize * (search.PageInfo.Page - 1) - limit := search.PageInfo.Page - db := global.GO_DB.Where(search.User) - err = db.Count(&searchResult.Total).Error - if err != nil { - return - } - err = db.Offset(offset).Limit(limit).Find(&users).Error - if err != nil { - return - } - searchResult.Page = search.PageInfo.Page - searchResult.PageSize = search.PageInfo.PageSize - searchResult.List = users - return -} - -func GetUserById(id int) (user User, err error) { - err = global.GO_DB.Where("id = ?", id).First(&user).Error - return -} - -func GetUserByUsername(username string) (user User, err error) { - err = global.GO_DB.Where("username = ?", username).First(&user).Error - return -} - -func ExistUserById(id int64) bool { - var user User - global.GO_DB.Where("id = ?", id).First(&user) - - return user.ID > 0 -} - -func ExistUserByUsername(username string) bool { - var user User - global.GO_DB.Where("username = ?", username).First(&user) - - return user.ID > 0 -} - -func CreateUser(user User) (err error) { - err = global.GO_DB.Create(&user).Error - - return -} - -func UpdateUser(user *User) (err error) { - err = global.GO_DB.Save(&user).Error - return -} - -func DeleteUser(user *User) (err error) { - err = global.GO_DB.Delete(&user).Error - return -} - -func (user *User) CheckPassword(password string) bool { - return crypt.Md5Check(password, user.Password) -} diff --git a/internal/routers/basic.go b/internal/routers/basic.go index e25fdc3..ba5e70c 100644 --- a/internal/routers/basic.go +++ b/internal/routers/basic.go @@ -1,36 +1,18 @@ /* * @Date: 2021-03-21 19:54:57 * @LastEditors: viletyy - * @LastEditTime: 2021-06-10 15:16:54 + * @LastEditTime: 2021-06-10 17:51:43 * @FilePath: /potato/internal/routers/basic.go */ package routers -import ( - "github.com/viletyy/potato/internal/controller/api/v1/basic" -) - func V1InitBasicRouter() { - // metaDatabases := V1RouterGroup.Group("/meta_databases") - // { - // metaDatabases.GET("", basic.GetMetaDatabases) - // metaDatabases.POST("", basic.AddMetaDatabase) - // metaDatabases.PATCH("/:id", basic.EditMetaDatabase) - // metaDatabases.DELETE("/:id", basic.DeleteMetaDatabase) - // metaDatabases.GET("/:id/meta_tables", basic.GetMetaTables) - // } + vendors := V1RouterGroup.Group("/vendors") { - vendors.GET("", basic.GetVendors) - vendors.POST("", basic.CreateVendor) - vendors.PATCH("/:id", basic.UpdateVendor) - vendors.DELETE("/:id", basic.DeleteVendor) + vendors.GET("") + vendors.POST("") + vendors.PATCH("/:id") + vendors.DELETE("/:id") } - // businesses := V1RouterGroup.Group("/businesses") - // { - // businesses.GET("", basic.GetBusinesses) - // businesses.POST("", basic.AddBusiness) - // businesses.PATCH("/:id", basic.EditBusiness) - // businesses.DELETE("/:id", basic.DeleteBusiness) - // } } diff --git a/internal/routers/router.go b/internal/routers/router.go index e2684af..ec9009a 100644 --- a/internal/routers/router.go +++ b/internal/routers/router.go @@ -1,7 +1,7 @@ /* * @Date: 2021-03-21 19:54:57 * @LastEditors: viletyy - * @LastEditTime: 2021-06-10 15:17:07 + * @LastEditTime: 2021-06-10 19:02:31 * @FilePath: /potato/internal/routers/router.go */ package routers @@ -27,13 +27,13 @@ func InitRouter() *gin.Engine { Engine.Use(gin.Logger()) Engine.Use(gin.Recovery()) + Engine.Use(middleware.Translations()) gin.SetMode(global.GO_CONFIG.App.RunMode) Engine.Use(middleware.CORS()) - Engine.POST("/api/v1/auth", v1.Auth) - Engine.POST("/api/v1/register", v1.Register) + Engine.POST("/api/v1/auth", v1.GetAuth) Engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) V1InitModule() diff --git a/internal/service/auth.go b/internal/service/auth.go new file mode 100644 index 0000000..7649a73 --- /dev/null +++ b/internal/service/auth.go @@ -0,0 +1,27 @@ +/* + * @Date: 2021-06-10 18:55:46 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 18:58:09 + * @FilePath: /potato/internal/service/auth.go + */ +package service + +import "errors" + +type AuthRequest struct { + AppKey string `json:"app_key" validate:"required"` + AppSecret string `json:"app_secret" validate:"required"` +} + +func (svc *Service) CheckAuth(param *AuthRequest) error { + auth, err := svc.dao.GetAuth(param.AppKey, param.AppSecret) + if err != nil { + return err + } + + if auth.ID > 0 { + return nil + } + + return errors.New("auth info does not exist.") +} diff --git a/internal/service/service.go b/internal/service/service.go new file mode 100644 index 0000000..c6172e1 --- /dev/null +++ b/internal/service/service.go @@ -0,0 +1,26 @@ +/* + * @Date: 2021-06-10 18:51:48 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 18:53:10 + * @FilePath: /potato/internal/service/service.go + */ +package service + +import ( + "context" + + "github.com/viletyy/potato/global" + "github.com/viletyy/potato/internal/dao" +) + +type Service struct { + Ctx context.Context + dao *dao.Dao +} + +func New(ctx context.Context) Service { + svc := Service{Ctx: ctx} + svc.dao = dao.New(global.GO_DB) + + return svc +} diff --git a/internal/service/vendor.go b/internal/service/vendor.go new file mode 100644 index 0000000..1f0aba5 --- /dev/null +++ b/internal/service/vendor.go @@ -0,0 +1,30 @@ +/* + * @Date: 2021-06-10 17:57:48 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 18:01:40 + * @FilePath: /potato/internal/service/vendor.go + */ +package service + +type CountVendorRequest struct { + Name string `json:"name" validate:"max=100"` +} + +type ListVendorRequest struct { + Name string `json:"name" validate:"max=100"` +} + +type CreateVendorRequest struct { + Name string `json:"name" validate:"required"` + Uuid int `json:"uuid"` +} + +type UpdateVendorRequest struct { + ID int64 `json:"id" validate:"required,gte=1"` + Name string `json:"name"` + Uuid int `json:"uuid"` +} + +type DeleteVendorRequest struct { + ID int64 `json:"id" validate:"required,gte=1"` +} diff --git a/pkg/app/app.go b/pkg/app/app.go new file mode 100644 index 0000000..717703d --- /dev/null +++ b/pkg/app/app.go @@ -0,0 +1,54 @@ +/* + * @Date: 2021-06-10 16:47:58 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 17:25:49 + * @FilePath: /potato/pkg/app/app.go + */ +package app + +import ( + "github.com/gin-gonic/gin" + "github.com/viletyy/potato/pkg/errcode" +) + +type Response struct { + Ctx *gin.Context +} + +type Pager struct { + Page int `json:"page"` + PageSize int `json:"page_size"` + Total int `json:"total"` +} + +func NewResponse(ctx *gin.Context) *Response { + return &Response{Ctx: ctx} +} + +func (r *Response) ToResponse(data interface{}) { + err := errcode.Success + err.WithData(data) + + r.ToErrorResponse(err) +} + +func (r *Response) ToResponseList(list interface{}, total int) { + err := errcode.Success + err.WithData(map[string]interface{}{ + "list": list, + "pager": Pager{ + Page: GetPage(r.Ctx), + PageSize: GetPageSize(r.Ctx), + Total: total, + }, + }) + r.ToErrorResponse(err) +} + +func (r *Response) ToErrorResponse(err *errcode.Error) { + response := gin.H{"code": err.Code, "msg": err.Msg} + data := err.Data + response["data"] = data + + r.Ctx.JSON(err.StatusCode(), response) +} diff --git a/pkg/app/form.go b/pkg/app/form.go new file mode 100644 index 0000000..ea66898 --- /dev/null +++ b/pkg/app/form.go @@ -0,0 +1,60 @@ +/* + * @Date: 2021-06-10 18:10:14 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 18:16:12 + * @FilePath: /potato/pkg/app/form.go + */ +package app + +import ( + "strings" + + "github.com/gin-gonic/gin" + ut "github.com/go-playground/universal-translator" + "github.com/go-playground/validator/v10" +) + +type ValidError struct { + Key string + Message string +} + +type ValidErrors []*ValidError + +func (v *ValidError) Error() string { + return v.Message +} + +func (v ValidErrors) Error() string { + return strings.Join(v.Errors(), ",") +} + +func (v ValidErrors) Errors() (errs []string) { + for _, err := range v { + errs = append(errs, err.Error()) + } + return +} + +func BindAndValid(c *gin.Context, v interface{}) (bool, ValidErrors) { + var errs ValidErrors + err := c.ShouldBind(v) + if err != nil { + v := c.Value("trans") + trans, _ := v.(ut.Translator) + verrs, ok := err.(validator.ValidationErrors) + if !ok { + return false, errs + } + for key, value := range verrs.Translate(trans) { + errs = append(errs, &ValidError{ + Key: key, + Message: value, + }) + } + + return false, errs + } + + return true, nil +} diff --git a/pkg/app/jwt.go b/pkg/app/jwt.go new file mode 100644 index 0000000..098cab3 --- /dev/null +++ b/pkg/app/jwt.go @@ -0,0 +1,60 @@ +/* + * @Date: 2021-06-10 18:25:19 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 18:41:57 + * @FilePath: /potato/pkg/app/jwt.go + */ +package app + +import ( + "time" + + "github.com/dgrijalva/jwt-go" + "github.com/viletyy/potato/global" + "github.com/viletyy/yolk/crypt" +) + +type Claims struct { + AppKey string `json:"app_key"` + AppSecret string `json:"app_secret"` + jwt.StandardClaims +} + +func GetJWTSecret() []byte { + return []byte(global.GO_CONFIG.App.JwtSecret) +} + +func GenerateToken(appKey, appSecret string) (string, error) { + nowTime := time.Now() + expireTime := nowTime.Add(time.Duration(global.GO_CONFIG.App.JwtExpire)) + claims := Claims{ + AppKey: crypt.Md5Encode(appKey), + AppSecret: crypt.Md5Encode(appSecret), + StandardClaims: jwt.StandardClaims{ + ExpiresAt: expireTime.Unix(), + Issuer: global.GO_CONFIG.App.JwtIssuser, + }, + } + + tokenClaims := jwt.NewWithClaims(jwt.SigningMethodES256, claims) + token, err := tokenClaims.SignedString(GetJWTSecret()) + return token, err +} + +func ParseToken(token string) (*Claims, error) { + tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) { + return GetJWTSecret(), nil + }) + + if err != nil { + return nil, err + } + + if tokenClaims != nil { + if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid { + return claims, nil + } + } + + return nil, err +} diff --git a/pkg/app/paginator.go b/pkg/app/paginator.go new file mode 100644 index 0000000..5baaaf0 --- /dev/null +++ b/pkg/app/paginator.go @@ -0,0 +1,46 @@ +/* + * @Date: 2021-06-10 15:27:36 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 16:58:28 + * @FilePath: /potato/pkg/app/paginator.go + */ +package app + +import ( + "github.com/gin-gonic/gin" + "github.com/viletyy/potato/global" + "github.com/viletyy/yolk/convert" +) + +func GetPageInfo(c *gin.Context) (page, pageSize int) { + page, _ = convert.StrTo(c.DefaultQuery("page", "1")).Int() + pageSize, _ = convert.StrTo(c.DefaultQuery("page_size", "10")).Int() + return +} + +func GetPage(c *gin.Context) int { + page, _ := convert.StrTo(c.Query("page")).Int() + if page <= 0 { + return 1 + } + + return page +} + +func GetPageSize(c *gin.Context) int { + pageSize, _ := convert.StrTo(c.Query("page_size")).Int() + if pageSize <= 0 { + return int(global.GO_CONFIG.App.PageSize) + } + + return pageSize +} + +func GetPageOffset(page, pageSize int) int { + result := 0 + if page > 0 { + result = (page - 1) * pageSize + } + + return result +} diff --git a/pkg/errcode/common_code.go b/pkg/errcode/common_code.go new file mode 100644 index 0000000..cffc3b3 --- /dev/null +++ b/pkg/errcode/common_code.go @@ -0,0 +1,19 @@ +/* + * @Date: 2021-06-10 16:25:21 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 16:30:03 + * @FilePath: /potato/pkg/errcode/common_code.go + */ +package errcode + +var ( + Success = NewError(0, "请求成功") + ServerError = NewError(10000, "服务内部错误") + InvalidParams = NewError(10001, "参数错误") + NotFound = NewError(10002, "找不到数据") + UnauthorizedAuthNotExist = NewError(10003, "鉴权失败,找不到对应等 AppKey和 AppSecret") + UnauthorizedTokenError = NewError(10004, "鉴权失败,Token 错误") + UnauthorizedTokenTimeout = NewError(10005, "鉴权失败,Token 超时") + UnauthorizedTokenGenerate = NewError(10006, "鉴权失败,Token 生成失败") + TooManyRequests = NewError(10007, "请求过多") +) diff --git a/pkg/errcode/errcode.go b/pkg/errcode/errcode.go new file mode 100644 index 0000000..b652d0e --- /dev/null +++ b/pkg/errcode/errcode.go @@ -0,0 +1,63 @@ +/* + * @Date: 2021-06-10 16:30:10 + * @LastEditors: viletyy + * @LastEditTime: 2021-06-10 17:27:59 + * @FilePath: /potato/pkg/errcode/errcode.go + */ +package errcode + +import ( + "fmt" + "net/http" +) + +type Error struct { + Code int `json:"code"` + Msg string `json:"msg"` + Data interface{} `json:"data,omitempty"` +} + +var codes = map[int]string{} + +func NewError(code int, msg string) *Error { + if _, ok := codes[code]; ok { + panic(fmt.Sprintf("错误码 %d 已存在,请更换一个", code)) + } + codes[code] = msg + return &Error{Code: code, Msg: msg} +} + +func (e *Error) Error() string { + return fmt.Sprintf("错误码:%d,错误信息:%s", e.Code, e.Msg) +} + +func (e *Error) Msgf(args []interface{}) string { + return fmt.Sprintf(e.Msg, args...) +} + +func (e *Error) WithData(data interface{}) { + e.Data = data +} + +func (e *Error) StatusCode() int { + switch e.Code { + case Success.Code: + return http.StatusOK + case ServerError.Code: + return http.StatusInternalServerError + case InvalidParams.Code: + return http.StatusBadRequest + case UnauthorizedAuthNotExist.Code: + fallthrough + case UnauthorizedTokenError.Code: + fallthrough + case UnauthorizedTokenGenerate.Code: + fallthrough + case UnauthorizedTokenTimeout.Code: + return http.StatusUnauthorized + case TooManyRequests.Code: + return http.StatusTooManyRequests + } + + return http.StatusInternalServerError +} diff --git a/pkg/paginator.go b/pkg/paginator.go deleted file mode 100644 index 625b8e9..0000000 --- a/pkg/paginator.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * @Date: 2021-06-10 15:27:36 - * @LastEditors: viletyy - * @LastEditTime: 2021-06-10 15:52:48 - * @FilePath: /potato/pkg/paginator.go - */ -package pkg - -import ( - "github.com/gin-gonic/gin" - "github.com/viletyy/yolk/convert" -) - -func GetPageInfo(c *gin.Context) (page, pageSize int) { - page, _ = convert.StrTo(c.DefaultQuery("page", "1")).Int() - pageSize, _ = convert.StrTo(c.DefaultQuery("page_size", "10")).Int() - return -} diff --git a/pkg/request.go b/pkg/request.go deleted file mode 100644 index dc15064..0000000 --- a/pkg/request.go +++ /dev/null @@ -1,19 +0,0 @@ -/* - * @Date: 2021-03-22 23:46:49 - * @LastEditors: viletyy - * @LastEditTime: 2021-06-10 15:18:09 - * @FilePath: /potato/pkg/request.go - */ -package pkg - -type PageInfo struct { - Page int `json:"page"` - PageSize int `json:"page_size"` -} - -type SearchResult struct { - List interface{} `json:"list"` - Total int64 `json:"total"` - Page int `json:"page"` - PageSize int `json:"page_size"` -} diff --git a/pkg/response.go b/pkg/response.go deleted file mode 100644 index a241343..0000000 --- a/pkg/response.go +++ /dev/null @@ -1,64 +0,0 @@ -/* - * @Date: 2021-03-22 18:51:29 - * @LastEditors: viletyy - * @LastEditTime: 2021-06-10 15:18:18 - * @FilePath: /potato/pkg/response.go - */ -package pkg - -import ( - "net/http" - - "github.com/gin-gonic/gin" -) - -type Response struct { - Code int `json:"code"` - Data interface{} `json:"data"` - Msg string `json:"msg"` -} - -const ( - ERROR = -1 - SUCCESS = 0 -) - -func Result(code int, data interface{}, msg string, c *gin.Context) { - c.JSON(http.StatusOK, Response{ - code, - data, - msg, - }) -} - -func Ok(c *gin.Context) { - Result(SUCCESS, map[string]interface{}{}, "操作成功", c) -} - -func OkWithMessage(message string, c *gin.Context) { - Result(SUCCESS, map[string]interface{}{}, message, c) -} - -func OkWithData(data interface{}, c *gin.Context) { - Result(SUCCESS, data, "操作成功", c) -} - -func OkWithDetailed(data interface{}, message string, c *gin.Context) { - Result(SUCCESS, data, message, c) -} - -func Fail(c *gin.Context) { - Result(ERROR, map[string]interface{}{}, "操作失败", c) -} - -func FailWithMessage(message string, c *gin.Context) { - Result(ERROR, map[string]interface{}{}, message, c) -} - -func FailWithData(data interface{}, c *gin.Context) { - Result(ERROR, data, "操作失败", c) -} - -func FailWithDetailed(data interface{}, message string, c *gin.Context) { - Result(ERROR, data, message, c) -}