From 4acbcc8932365897d712d469ac65ca342d738395 Mon Sep 17 00:00:00 2001 From: viletyy Date: Wed, 23 Sep 2020 09:14:27 +0800 Subject: [PATCH] =?UTF-8?q?[ADD]=E6=9F=A5=E7=9C=8B=E5=91=98=E5=B7=A5?= =?UTF-8?q?=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 20 ++++++++++++ conf/app.ini | 6 ++-- docs/docs.go | 34 ++++++++++++++++++++- docs/swagger.json | 34 ++++++++++++++++++++- docs/swagger.yaml | 23 +++++++++++++- go.mod | 11 ++++++- middleware/jwt/jwt.go | 6 ++-- models/employee.go | 59 ++++++++++++++++++++++++++++++++---- pkg/e/code.go | 20 ++++++------ pkg/e/msg.go | 19 ++++++------ routers/admin.go | 6 ++++ routers/admin/login.go | 8 ++--- routers/admin/v1/employee.go | 37 +++++++++++++++++++++- 13 files changed, 241 insertions(+), 42 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fdfedfa --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +# Created by .ignore support plugin (hsz.mobi) +### Go template +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ +go.sum +.idea/* +runtime/* \ No newline at end of file diff --git a/conf/app.ini b/conf/app.ini index 1b00b8b..ba64af8 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -11,9 +11,9 @@ WRITE_TIMEOUT = 60 [database] TYPE = postgres -USER = postgres +USER = virus PASSWORD = a19960425 HOST = 0.0.0.0 PORT = 5432 -NAME = blog -TABLE_PREFIX = blog_ +NAME = shop +TABLE_PREFIX = shop_ diff --git a/docs/docs.go b/docs/docs.go index 4a344da..4dc8bcd 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -26,7 +26,7 @@ var doc = `{ "basePath": "{{.BasePath}}", "paths": { "/admin/login": { - "post": { + "get": { "produces": [ "application/json" ], @@ -99,6 +99,38 @@ var doc = `{ } } } + }, + "/admin/v1/employees/{id}": { + "get": { + "produces": [ + "application/json" + ], + "summary": "获取单个员工", + "parameters": [ + { + "type": "string", + "description": "Token", + "name": "token", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "{\"code\": 200, \"data\": {}, \"msg\": \"ok\"}", + "schema": { + "type": "string" + } + } + } + } } } }` diff --git a/docs/swagger.json b/docs/swagger.json index 0063ce8..c640c79 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -6,7 +6,7 @@ }, "paths": { "/admin/login": { - "post": { + "get": { "produces": [ "application/json" ], @@ -79,6 +79,38 @@ } } } + }, + "/admin/v1/employees/{id}": { + "get": { + "produces": [ + "application/json" + ], + "summary": "获取单个员工", + "parameters": [ + { + "type": "string", + "description": "Token", + "name": "token", + "in": "query", + "required": true + }, + { + "type": "integer", + "description": "ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "{\"code\": 200, \"data\": {}, \"msg\": \"ok\"}", + "schema": { + "type": "string" + } + } + } + } } } } \ No newline at end of file diff --git a/docs/swagger.yaml b/docs/swagger.yaml index f33328d..6bdf787 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -3,7 +3,7 @@ info: license: {} paths: /admin/login: - post: + get: parameters: - description: 用户名 in: query @@ -51,4 +51,25 @@ paths: schema: type: string summary: 获取员工列表 + /admin/v1/employees/{id}: + get: + parameters: + - description: Token + in: query + name: token + required: true + type: string + - description: ID + in: path + name: id + required: true + type: integer + produces: + - application/json + responses: + "200": + description: '{"code": 200, "data": {}, "msg": "ok"}' + schema: + type: string + summary: 获取单个员工 swagger: "2.0" diff --git a/go.mod b/go.mod index 1205175..1481bfb 100644 --- a/go.mod +++ b/go.mod @@ -5,19 +5,28 @@ go 1.15 require ( github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 github.com/astaxie/beego v1.12.2 + github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/gin-gonic/gin v1.6.3 github.com/go-ini/ini v1.61.0 + github.com/go-openapi/spec v0.19.9 // indirect + github.com/go-openapi/swag v0.19.9 // indirect github.com/go-playground/validator/v10 v10.3.0 // indirect github.com/jinzhu/gorm v1.9.16 github.com/lib/pq v1.2.0 // indirect + github.com/mailru/easyjson v0.7.6 // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 // indirect github.com/swaggo/gin-swagger v1.2.0 - github.com/swaggo/swag v1.5.1 + github.com/swaggo/swag v1.6.7 github.com/ugorji/go v1.1.8 // indirect github.com/unknwon/com v1.0.1 + github.com/urfave/cli v1.22.4 // indirect + github.com/urfave/cli/v2 v2.2.0 // indirect golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect + golang.org/x/net v0.0.0-20200904194848-62affa334b73 // indirect golang.org/x/sys v0.0.0-20200909081042-eff7692f9009 // indirect + golang.org/x/tools v0.0.0-20200921210052-fa0125251cc4 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect google.golang.org/protobuf v1.25.0 // indirect gopkg.in/ini.v1 v1.61.0 // indirect diff --git a/middleware/jwt/jwt.go b/middleware/jwt/jwt.go index 8cae3ad..f98deed 100644 --- a/middleware/jwt/jwt.go +++ b/middleware/jwt/jwt.go @@ -15,13 +15,13 @@ func JWT() gin.HandlerFunc { code = e.SUCCESS token := c.Query("token") if token == "" { - code = e.INVALID_PARAMS + code = e.InvalidParams } else { claims, err := util.ParseToken(token) if err != nil { - code = e.ERROR_AUTH_CHECK_TOKEN_FAIL + code = e.ErrorAuthCheckTokenFail } else if time.Now().Unix() > claims.ExpiresAt { - code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT + code = e.ErrorAuthCheckTokenTimeout } } if code != e.SUCCESS { diff --git a/models/employee.go b/models/employee.go index 29ec14c..433f3dd 100644 --- a/models/employee.go +++ b/models/employee.go @@ -1,23 +1,42 @@ package models +import ( + "github.com/jinzhu/gorm" + "time" +) + type Employee struct { - ID int `gorm:"primary_key" json:"id"` - Username string `json:"username"` - Password string `json:"password"` + ID int `gorm:"primary_key" json:"id"` + Username string `json:"username"` + Password string `json:"password"` Department string `json:"department"` - Position string `json:"position"` - State int `json:"state"` + Position string `json:"position"` + State int `json:"state"` + CreatedOn int `json:"created_on"` + ModifiedOn int `json:"modified_on"` } func CheckEmployee(username, password string) bool { var employee Employee db.Select("id").Where(Employee{Username: username, Password: password}).First(&employee) + if employee.ID > 0 { return true } return false } +func ExistEmployeeByID(id int) bool { + var employee Employee + db.Select("id").Where("id = ?", id).First(&employee) + + if employee.ID > 0 { + return true + } + + return false +} + func GetEmployeeTotal(maps interface{}) (count int) { db.Model(&Employee{}).Where(maps).Count(&count) @@ -28,4 +47,32 @@ func GetEmployees(pageNum int, pageSize int, maps interface{}) (employees []Empl db.Where(maps).Offset(pageNum).Limit(pageSize).Find(&employees) return -} \ No newline at end of file +} + +func GetEmployee(id int) (employee Employee) { + db.Where("id = ?", id).First(&employee) + return +} + +func EditEmployee(id int, data interface{}) bool { + db.Model(&Employee{}).Where("id = ?", id).Updates(data) + + return true +} + +func AddArticle(data map[string]interface{}) bool { + db.Create(&Employee{ + Username: data["username"].(string), + Password: data["password"].(string), + Department: data["department"].(string), + Position: data["position"].(string), + State: data["state"].(int), + }) + return true +} + +func (employee *Employee) BeforeUpdate(scope *gorm.Scope) error { + scope.SetColumn("ModifiedOn", time.Now().Unix()) + + return nil +} diff --git a/pkg/e/code.go b/pkg/e/code.go index 5f0773b..0c1240d 100644 --- a/pkg/e/code.go +++ b/pkg/e/code.go @@ -1,16 +1,14 @@ package e const ( - SUCCESS = 200 - ERROR = 500 - INVALID_PARAMS = 400 + SUCCESS = 200 + ERROR = 500 + InvalidParams = 400 + ErrorAuthCheckTokenFail = 10001 + ErrorAuthCheckTokenTimeout = 10002 + ErrorAuthToken = 10003 + ErrorAuth = 10004 - ERROR_EXIST_TAG = 10001 - ERROR_NOT_EXIST_TAG = 10002 - ERROR_NOT_EXIST_ARTICLE = 10003 - - ERROR_AUTH_CHECK_TOKEN_FAIL = 20001 - ERROR_AUTH_CHECK_TOKEN_TIMEOUT = 20002 - ERROR_AUTH_TOKEN = 20003 - ERROR_AUTH = 20004 + ErrorExistEmployee = 20001 + ErrorNotExistEmployee = 20002 ) diff --git a/pkg/e/msg.go b/pkg/e/msg.go index cf21a30..f2e1bea 100644 --- a/pkg/e/msg.go +++ b/pkg/e/msg.go @@ -1,16 +1,15 @@ package e var MsgFlags = map[int]string{ - SUCCESS: "ok", - ERROR: "fail", - INVALID_PARAMS: "请求参数错误", - ERROR_EXIST_TAG: "已存在该标签名称", - ERROR_NOT_EXIST_TAG: "该标签不存在", - ERROR_NOT_EXIST_ARTICLE: "该文章不存在", - ERROR_AUTH_CHECK_TOKEN_FAIL: "TOKEN鉴权失败", - ERROR_AUTH_CHECK_TOKEN_TIMEOUT: "TOKEN已超时", - ERROR_AUTH_TOKEN: "TOKEN生成失败", - ERROR_AUTH: "TOKEN错误", + SUCCESS: "ok", + ERROR: "fail", + InvalidParams: "请求参数错误", + ErrorAuthCheckTokenFail: "TOKEN鉴权失败", + ErrorAuthCheckTokenTimeout: "TOKEN已超时", + ErrorAuthToken: "TOKEN生成失败", + ErrorAuth: "TOKEN错误", + ErrorExistEmployee: "已存在该员工用户名", + ErrorNotExistEmployee: "该员工不存在", } func GetMsg(code int) string { diff --git a/routers/admin.go b/routers/admin.go index 18e8d71..1b1db8c 100644 --- a/routers/admin.go +++ b/routers/admin.go @@ -16,6 +16,12 @@ func InitAdmin(r *gin.Engine) *gin.Engine { { // 获取员工列表 adminv1.GET("/employees", v1.GetEmployees) + // 获取指定员工列表 + adminv1.GET("/employees/:id", v1.GetEmployee) + //// 新建员工 + //adminv1.POST("/employees", v1.AddEmployee) + //// 更新指定员工 + //adminv1.PUT("/employees/:id", v1.EditArticle) } return r diff --git a/routers/admin/login.go b/routers/admin/login.go index df71d78..a9c5635 100644 --- a/routers/admin/login.go +++ b/routers/admin/login.go @@ -20,7 +20,7 @@ type Employee struct { // @Param username query string true "用户名" // @Param password query string true "密码" // @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}" -// @Router /admin/login [post] +// @Router /admin/login [get] func GetLogin(c *gin.Context) { username := c.Query("username") password := c.Query("password") @@ -28,19 +28,19 @@ func GetLogin(c *gin.Context) { a := Employee{Username: username, Password: password} ok, _ := valid.Valid(&a) data := make(map[string]interface{}) - code := e.INVALID_PARAMS + code := e.InvalidParams if ok { isExist := models.CheckEmployee(username, password) if isExist { token, err := util.GenerateToken(username, password) if err != nil { - code = e.ERROR_AUTH_TOKEN + code = e.ErrorAuthToken } else { data["token"] = token code = e.SUCCESS } } else { - code = e.ERROR_AUTH + code = e.ErrorAuth } } else { for _, err := range valid.Errors { diff --git a/routers/admin/v1/employee.go b/routers/admin/v1/employee.go index 951915c..7628394 100644 --- a/routers/admin/v1/employee.go +++ b/routers/admin/v1/employee.go @@ -12,6 +12,40 @@ import ( "net/http" ) +// @Summary 获取单个员工 +// @Produce json +// @Param token query string true "Token" +// @Param id path int true "ID" +// @Success 200 {string} json "{"code": 200, "data": {}, "msg": "ok"}" +// @Router /admin/v1/employees/{id} [GET] +func GetEmployee(c *gin.Context) { + id := com.StrTo(c.Param("id")).MustInt() + + valid := validation.Validation{} + valid.Min(id, 1, "id").Message("ID必须大于0") + + code := e.InvalidParams + var data interface{} + if !valid.HasErrors() { + if models.ExistEmployeeByID(id) { + data = models.GetEmployee(id) + code = e.SUCCESS + } else { + code = e.ErrorNotExistEmployee + } + } else { + for _, err := range valid.Errors { + logging.Info("err.key: %s, err.message: %s", err.Key, err.Message) + } + } + + c.JSON(http.StatusOK, gin.H{ + "code" : code, + "msg" : e.GetMsg(code), + "data" : data, + }) +} + // @Summary 获取员工列表 // @Produce json // @Param token query string true "Token" @@ -31,7 +65,7 @@ func GetEmployees(c *gin.Context) { valid.Range(state, 0, 1, "state").Message("状态只允许0或1") } - code := e.INVALID_PARAMS + code := e.InvalidParams if ! valid.HasErrors() { code = e.SUCCESS @@ -49,3 +83,4 @@ func GetEmployees(c *gin.Context) { "data" : data, }) } +