大面积重构

Response部分

usersController部分

中间件部分
This commit is contained in:
Eigeen 2022-04-06 13:54:48 +08:00
parent 513b563728
commit 0df2aaa82f
13 changed files with 114 additions and 119 deletions

View File

@ -13,15 +13,15 @@ func init() {
} }
func main() { func main() {
// 加载配置
config.SetupConfig()
// 初始化数据库 // 初始化数据库
err := dao.Conn() err := dao.Conn()
if err != nil { if err != nil {
golog.Fatal("数据库初始化失败: ", err) golog.Fatal("数据库初始化失败: ", err)
} }
// 加载配置
config.SetupConfig()
// 启动服务 // 启动服务
app := router.Router() app := router.Router()
app.Run(iris.Addr(":8080")) app.Run(iris.Addr(":8080"))

View File

@ -2,6 +2,9 @@ package model
import ( import (
"drive-linked/pkg/dao" "drive-linked/pkg/dao"
"fmt"
"github.com/jmoiron/sqlx"
"strings"
) )
type User struct { type User struct {
@ -15,18 +18,22 @@ type User struct {
Roles string `json:"roles"` Roles string `json:"roles"`
} }
func (user *User) GetByName(name string) (err error) { func (user *User) GetWithConditions(conditions *map[string]interface{}) error {
err = dao.DB.Get(user, "SELECT * FROM users WHERE name=?", name) // 支持多条件查询
if err != nil { //TODO:分离多条件查询部分,有利于代码复用
return err var where []string
} var values []interface{}
return nil
for k, v := range *conditions {
values = append(values, v)
where = append(where, fmt.Sprintf(`"%s" = %s`, k, "?"))
} }
func (user *User) GetByEmail(email string) (err error) { exec := sqlx.Rebind(sqlx.QUESTION, `SELECT * FROM users WHERE `+strings.Join(where, "AND")+" LIMIT 1")
err = dao.DB.Get(user, "SELECT * FROM users WHERE email=?", email) err := dao.DB.Get(user, exec, values...)
if err != nil { if err != nil {
return err return err
} }
return nil return nil
} }

View File

@ -1,30 +1,22 @@
package model package model
import ( import (
"database/sql"
"drive-linked/pkg/dao" "drive-linked/pkg/dao"
"testing" "testing"
) )
func init() { func TestUser_GetWithConditions(t *testing.T) {
err := dao.Conn() dao.Conn()
if err != nil {
return
}
}
func TestUser_GetUser(t *testing.T) {
var user User var user User
// 存在的用户 // 存在的用户
err := user.GetByName("eigeen") conditions := &map[string]interface{}{
"name": "eigeen",
"email": "375109735@qq.com",
}
err := user.GetWithConditions(conditions)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
t.Log(user) t.Log(user)
// 不存在的用户
err = user.GetByName("unknown_user")
if err != sql.ErrNoRows {
t.Error(err)
}
} }

View File

@ -3,7 +3,6 @@ package common
import ( import (
"drive-linked/config" "drive-linked/config"
"github.com/golang-jwt/jwt/v4" "github.com/golang-jwt/jwt/v4"
"strings"
"time" "time"
) )
@ -13,16 +12,8 @@ type JwtClaims struct {
} }
//TODO:token解密验证 //TODO:token解密验证
func ValidateLogin(authorization string) error { func VerifyToken(authorization string) error {
// 取出Bearer后的内容 token, err := jwt.Parse(authorization, func(token *jwt.Token) (interface{}, error) {
var tokenString string
if auths := strings.Split(authorization, " "); len(auths) > 1 {
tokenString = auths[1]
} else {
return jwt.ErrInvalidKey
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(config.Cfg.Security.Jwt.Secret), nil return []byte(config.Cfg.Security.Jwt.Secret), nil
}) })

View File

@ -19,7 +19,7 @@ func TestValidateLogin(t *testing.T) {
config.SetupConfig() config.SetupConfig()
tokenString, _ := NewToken("eigeen") tokenString, _ := NewToken("eigeen")
err := ValidateLogin(tokenString) err := VerifyToken(tokenString)
if err == nil { if err == nil {
t.Log("验证通过") t.Log("验证通过")
} else { } else {

View File

@ -1,38 +0,0 @@
package controller
import (
"drive-linked/pkg/dto"
"drive-linked/pkg/service"
"encoding/json"
"github.com/kataras/iris/v12"
"io/ioutil"
"net/http"
)
func UserProfile(ctx iris.Context) {
serv := service.NewUsersService(ctx)
switch ctx.Request().Method {
// GET
case http.MethodGet:
serv.GetOneUser(ctx.Params().GetString("name"), service.MethodUserName)
return
// POST
case http.MethodPost:
//TODO:错误处理
body, err := ioutil.ReadAll(ctx.Request().Body)
if err != nil {
return
}
var req dto.QueryUserParams
err = json.Unmarshal(body, &req)
if err != nil {
return
}
serv.GetOneUser(req.Value, req.Method)
return
}
}

37
pkg/dao/sentences.go Normal file
View File

@ -0,0 +1,37 @@
package dao
import (
"fmt"
"strings"
)
type Conditions *map[string]interface{}
//TODO:未完成的sql语句构建器
type QuerySql struct {
Table string
Tail string
Conditions Conditions
Rebind int
body string
}
func (b *QuerySql) Build() {
if b.Conditions == nil {
}
var where []string
var values []interface{}
for k, v := range *b.Conditions {
values = append(values, v)
where = append(where, fmt.Sprintf(`"%s"=%s`, k, "?"))
}
b.body = "SELECT * FROM " + b.Table + " WHERE " + strings.Join(where, "AND")
}
func (b *QuerySql) String() {
}

View File

@ -2,6 +2,7 @@ package dto
import ( import (
"drive-linked/pkg/serializer" "drive-linked/pkg/serializer"
"github.com/kataras/golog"
"github.com/kataras/iris/v12" "github.com/kataras/iris/v12"
"net/http" "net/http"
) )
@ -10,21 +11,18 @@ type Response struct {
Ctx iris.Context Ctx iris.Context
} }
const errJsonUnmarshalMsg = "{\"code\":500,\"msg\":\"Json解析错误请联系管理员\",\"data\":null}"
func NewResponse(ctx iris.Context) *Response { func NewResponse(ctx iris.Context) *Response {
return &Response{Ctx: ctx} return &Response{Ctx: ctx}
} }
const errJsonUnmarshalMsg = "{\"code\":500,\"msg\":\"Json解析错误请联系管理员\",\"data\":null}"
// 成功 统一处理 // 成功 统一处理
func (r *Response) Success(data interface{}) { func (r *Response) Success(data interface{}) {
res := serializer.Response{ resp := serializer.ResponseSerial{Code: http.StatusOK, Data: data}
Code: 200, _, err := r.Ctx.JSON(resp)
Msg: "",
Data: data,
}
_, err := r.Ctx.JSON(res)
if err != nil { if err != nil {
golog.Error("Json解析错误: ", resp)
r.Ctx.Write([]byte(errJsonUnmarshalMsg)) r.Ctx.Write([]byte(errJsonUnmarshalMsg))
return return
} }
@ -32,12 +30,8 @@ func (r *Response) Success(data interface{}) {
// 失败 统一处理 // 失败 统一处理
func (r *Response) Error(code int, msg string) { func (r *Response) Error(code int, msg string) {
res := serializer.Response{ resp := serializer.ResponseSerial{Code: code, Msg: msg}
Code: code, _, err := r.Ctx.JSON(resp)
Msg: msg,
Data: nil,
}
_, err := r.Ctx.JSON(res)
if err != nil { if err != nil {
r.Ctx.Write([]byte(errJsonUnmarshalMsg)) r.Ctx.Write([]byte(errJsonUnmarshalMsg))
return return

View File

@ -4,14 +4,23 @@ import (
"drive-linked/pkg/common" "drive-linked/pkg/common"
"drive-linked/pkg/dto" "drive-linked/pkg/dto"
"github.com/kataras/iris/v12" "github.com/kataras/iris/v12"
"strings"
) )
func SignRequired(ctx iris.Context) { func SignRequired(ctx iris.Context) {
auth := ctx.GetHeader("Authorization") auth := ctx.GetHeader("Authorization")
//TODO:更详细的判断,包括请求格式是否正确 //TODO:更详细的判断,包括请求格式是否正确
// 取出Bearer后的内容
var tokenString string
if auths := strings.Split(auth, " "); len(auths) > 1 {
tokenString = auths[1]
} else {
ctx.Skip()
}
// 验证token // 验证token
err := common.ValidateLogin(auth) err := common.VerifyToken(tokenString)
if err == nil { if err == nil {
ctx.Values().Set("logged_in", true) ctx.Values().Set("logged_in", true)
ctx.Next() ctx.Next()

View File

@ -1,8 +1,6 @@
package serializer package serializer
import "net/http" type ResponseSerial struct {
type Response struct {
Code int `json:"code"` Code int `json:"code"`
Msg string `json:"msg"` Msg string `json:"msg"`
Data interface{} `json:"data"` Data interface{} `json:"data"`
@ -10,17 +8,9 @@ type Response struct {
/* /*
自定义错误码 自定义错误码
10000 用户操作 40000 业务逻辑错误
50000 服务器操作
*/ */
const ( const (
ErrNoUser = 10001 ErrNoUser = 40001
) )
func Success(data interface{}) Response {
r := Response{
Code: http.StatusOK,
Msg: "",
Data: data,
}
return r
}

View File

@ -0,0 +1,20 @@
package controller
import (
"drive-linked/pkg/service"
"github.com/kataras/iris/v12"
)
func UserProfile(ctx iris.Context) {
serv := service.NewUsersService(ctx)
// 获取所有查询条件参数
var conditions map[string]interface{}
for _, field := range service.UserConditions {
if ctx.Params().GetString(field) != "" {
conditions[field] = ctx.Params().GetString(field)
}
}
serv.GetOneUser(&conditions)
ctx.Next()
}

View File

@ -13,26 +13,20 @@ type UsersService struct {
Ctx iris.Context Ctx iris.Context
} }
const ( var (
MethodUserName = "name" UserConditions = [...]string{"id", "name", "email", "nickname"}
MethodUserEmail = "email"
) )
func NewUsersService(ctx iris.Context) *UsersService { func NewUsersService(ctx iris.Context) *UsersService {
return &UsersService{Ctx: ctx} return &UsersService{Ctx: ctx}
} }
func (serv *UsersService) GetOneUser(field, method string) { func (serv *UsersService) GetOneUser(conditions *map[string]interface{}) {
var err error var err error
resp := dto.NewResponse(serv.Ctx) resp := dto.NewResponse(serv.Ctx)
user := &model.User{} user := &model.User{}
switch method { err = user.GetWithConditions(conditions)
case MethodUserName:
err = user.GetByName(field)
case MethodUserEmail:
err = user.GetByEmail(field)
}
switch err { switch err {
case nil: case nil:

View File

@ -1,8 +1,8 @@
package router package router
import ( import (
"drive-linked/pkg/controller"
"drive-linked/pkg/middleware" "drive-linked/pkg/middleware"
"drive-linked/pkg/service/controller"
"github.com/kataras/iris/v12" "github.com/kataras/iris/v12"
) )
@ -20,8 +20,7 @@ func Router() *iris.Application {
// 需要登录 // 需要登录
users.Use(middleware.SignRequired) users.Use(middleware.SignRequired)
// 用户详细信息 // 用户详细信息
users.Get("/profile/{name:string}", controller.UserProfile) users.Get("/profile", controller.UserProfile)
users.Post("/profile", controller.UserProfile)
}) })
return app return app
} }