Skip to content

Commit

Permalink
Merge pull request #24 from go-admin-team/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
wenjianzhang authored Jul 14, 2021
2 parents 26b4cc9 + 145dc00 commit 96084b1
Show file tree
Hide file tree
Showing 8 changed files with 287 additions and 5 deletions.
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ require (
github.com/bsm/redislock v0.5.0
github.com/fsnotify/fsnotify v1.4.7
github.com/ghodss/yaml v1.0.0
github.com/gin-gonic/gin v1.7.1
github.com/gin-gonic/gin v1.7.2
github.com/go-redis/redis/v7 v7.4.0
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0
github.com/google/uuid v1.1.2
Expand All @@ -32,6 +32,6 @@ require (
google.golang.org/grpc v1.29.1
google.golang.org/protobuf v1.26.0-rc.1
gorm.io/driver/mysql v1.0.3
gorm.io/gorm v1.21.10
gorm.io/gorm v1.21.11
gorm.io/plugin/dbresolver v1.1.0
)
133 changes: 133 additions & 0 deletions sdk/antd_api/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package antd_apis

import (
"errors"
"fmt"
vd "github.com/bytedance/go-tagexpr/v2/validator"
"github.com/gin-gonic/gin/binding"
"github.com/go-admin-team/go-admin-core/sdk/service"
"net/http"
"strconv"

"github.com/gin-gonic/gin"
"github.com/go-admin-team/go-admin-core/logger"
"github.com/go-admin-team/go-admin-core/sdk/api"
"github.com/go-admin-team/go-admin-core/sdk/pkg"
"github.com/go-admin-team/go-admin-core/sdk/pkg/response/antd"
"gorm.io/gorm"
)

type Api struct {
Context *gin.Context
Logger *logger.Helper
Orm *gorm.DB
Errors error
}

// GetLogger 获取上下文提供的日志
func (e Api) GetLogger() *logger.Helper {
return api.GetRequestLogger(e.Context)
}
// GetOrm 获取Orm DB
func (e *Api) GetOrm(c *gin.Context) (*gorm.DB, error) {
db, err := pkg.GetOrm(c)
if err != nil {
e.Error( http.StatusInternalServerError, "数据库连接获取失败", "9")
return nil, err
}
return db, nil
}

// Error 通常错误数据处理
// showType error display type: 0 silent; 1 message.warn; 2 message.error; 4 notification; 9 page
func (e *Api) Error( errCode int, errMsg string, showType string) {
if showType == "" {
showType = "2"
}
antd.Error(e.Context, strconv.Itoa(errCode), errMsg, showType)
}

// OK 通常成功数据处理
func (e *Api) OK( data interface{}) {
antd.OK(e.Context, data)
}

// PageOK 分页数据处理
func (e *Api) PageOK( result interface{}, total int, current int, pageSize int) {
antd.PageOK(e.Context, result, total, current, pageSize)
}

// Custom 兼容函数
func (e *Api) Custom( data gin.H) {
antd.Custum(e.Context, data)
}


// MakeContext 设置http上下文
func (e *Api) MakeContext(c *gin.Context) *Api {
e.Context = c
e.Logger = api.GetRequestLogger(c)
return e
}


// Bind 参数校验
func (e *Api) Bind(d interface{}, bindings ...binding.Binding) *Api {
var err error
if len(bindings) == 0 {
bindings = constructor.GetBindingForGin(d)
}
for i := range bindings {
if bindings[i] == nil {
err = e.Context.ShouldBindUri(d)
} else {
err = e.Context.ShouldBindWith(d, bindings[i])
}
if err != nil && err.Error() == "EOF" {
e.Logger.Warn("request body is not present anymore. ")
err = nil
continue
}
if err != nil {
e.AddError(err)
break
}
}
if err1 := vd.Validate(d); err1 != nil {
e.AddError(err1)
}
return e
}

// MakeOrm 设置Orm DB
func (e *Api) MakeOrm() *Api {
var err error
if e.Logger == nil {
err = errors.New("at MakeOrm logger is nil")
e.AddError(err)
return e
}
db, err := pkg.GetOrm(e.Context)
if err != nil {
e.Logger.Error(http.StatusInternalServerError, err, "数据库连接获取失败")
e.AddError(err)
}
e.Orm = db
return e
}

func (e *Api) MakeService(c *service.Service) *Api {
c.Log = e.Logger
c.Orm = e.Orm
return e
}

func (e *Api) AddError(err error) {
if e.Errors == nil {
e.Errors = err
} else if err != nil {
e.Logger.Error(err)
e.Errors = fmt.Errorf("%v; %w", e.Error, err)
}
}

110 changes: 110 additions & 0 deletions sdk/antd_api/binding.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package antd_apis

import (
"fmt"
"github.com/gin-gonic/gin/binding"
"reflect"
"strings"
"sync"
)

const (
_ uint8 = iota
json
xml
yaml
form
query
)

var constructor = &bindConstructor{}

type bindConstructor struct {
cache map[string][]uint8
mux sync.Mutex
}

func (e *bindConstructor) GetBindingForGin(d interface{}) []binding.Binding {
bs := e.getBinding(reflect.TypeOf(d).String())
if bs == nil {
//重新构建
bs = e.resolve(d)
}
gbs := make([]binding.Binding, 0)
mp := make(map[uint8]binding.Binding, 0)
for _, b := range bs {
switch b {
case json:
mp[json] = binding.JSON
case xml:
mp[xml] = binding.XML
case yaml:
mp[yaml] = binding.YAML
case form:
mp[form] = binding.Form
case query:
mp[query] = binding.Query
default:
mp[0] = nil
}
}
for e := range mp {
gbs=append(gbs, mp[e])
}
return gbs
}

func (e *bindConstructor) resolve(d interface{}) []uint8 {
bs := make([]uint8, 0)
qType := reflect.TypeOf(d).Elem()
var tag reflect.StructTag
var ok bool
fmt.Println(qType.Kind())
for i := 0; i < qType.NumField(); i++ {
tag = qType.Field(i).Tag
if _, ok = tag.Lookup("json"); ok {
bs = append(bs, json)
}
if _, ok = tag.Lookup("xml"); ok {
bs = append(bs, xml)
}
if _, ok = tag.Lookup("yaml"); ok {
bs = append(bs, yaml)
}
if _, ok = tag.Lookup("form"); ok {
bs = append(bs, form)
}
if _, ok = tag.Lookup("query"); ok {
bs = append(bs, query)
}
if _, ok = tag.Lookup("uri"); ok {
bs = append(bs, 0)
}
if t, ok := tag.Lookup("binding"); ok && strings.Index(t, "dive") > -1 {
qValue := reflect.ValueOf(d)
bs = append(bs, e.resolve(qValue.Field(i))...)
continue
}
if t, ok := tag.Lookup("validate"); ok && strings.Index(t, "dive") > -1 {
qValue := reflect.ValueOf(d)
bs = append(bs, e.resolve(qValue.Field(i))...)
}
}
return bs
}

func (e *bindConstructor) getBinding(name string) []uint8 {
e.mux.Lock()
defer e.mux.Unlock()
return e.cache[name]
}

func (e *bindConstructor) setBinding(name string, bs []uint8) {
e.mux.Lock()
defer e.mux.Unlock()
if e.cache == nil {
e.cache = make(map[string][]uint8)
}
e.cache[name] = bs
}

4 changes: 4 additions & 0 deletions sdk/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ func (e Api) Custom(data gin.H) {
response.Custum(e.Context, data)
}

func (e Api) Translate(form, to interface{}) {
pkg.Translate(form, to)
}

// getAcceptLanguage 获取当前语言
func (e *Api) getAcceptLanguage() string {
languages := language.ParseAcceptLanguage(e.Context.GetHeader("Accept-Language"), nil)
Expand Down
5 changes: 3 additions & 2 deletions sdk/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ go 1.14

require (
github.com/bsm/redislock v0.5.0
github.com/bytedance/go-tagexpr/v2 v2.7.12
github.com/casbin/casbin/v2 v2.24.0
github.com/chanxuehong/wechat v0.0.0-20201110083048-0180211b69fd
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gin-gonic/gin v1.7.1
github.com/gin-gonic/gin v1.7.2
github.com/go-admin-team/go-admin-core v1.3.5-rc.5
github.com/go-admin-team/go-admin-core/plugins/logger/zap v0.0.0-20210610020726-2db73adb505d
github.com/go-admin-team/gorm-adapter/v3 v3.2.1-0.20210310135230-1608cc35b95b
Expand All @@ -25,7 +26,7 @@ require (
github.com/slok/go-http-metrics v0.9.0
github.com/smartystreets/goconvey v1.6.4
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a
gorm.io/gorm v1.21.10
gorm.io/gorm v1.21.11
)

replace (
Expand Down
2 changes: 2 additions & 0 deletions sdk/pkg/response/antd/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ type response struct {
}

type Pages struct {
Response
Data interface{} `json:"data,omitempty"` // response data
Total int `json:"total,omitempty"`
Current int `json:"current,omitempty"`
PageSize int `json:"pageSize,omitempty"`
Expand Down
6 changes: 5 additions & 1 deletion sdk/pkg/response/antd/return.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ func PageOK(c *gin.Context, result interface{}, total int, current int, pageSize
res.Total = total
res.Current = current
res.PageSize = pageSize
OK(c, res)
res.Success = true
res.TraceId = pkg.GenerateMsgIDFromContext(c)
c.Set("result", res)
c.Set("status", http.StatusOK)
c.AbortWithStatusJSON(http.StatusOK, res)
}

// Custum 兼容函数
Expand Down
28 changes: 28 additions & 0 deletions sdk/pkg/translate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package pkg

import (
"reflect"
)

func Translate(form, to interface{}) {
fType := reflect.TypeOf(form)
fValue := reflect.ValueOf(form)
if fType.Kind() == reflect.Ptr {
fType = fType.Elem()
fValue = fValue.Elem()
}
tType := reflect.TypeOf(to)
tValue := reflect.ValueOf(to)
if tType.Kind() == reflect.Ptr {
tType = tType.Elem()
tValue = tValue.Elem()
}
for i := 0; i < fType.NumField(); i++ {
for j := 0; j < tType.NumField(); j++ {
if fType.Field(i).Name == tType.Field(j).Name &&
fType.Field(i).Type.ConvertibleTo(tType.Field(j).Type) {
tValue.Field(j).Set(fValue.Field(i))
}
}
}
}

0 comments on commit 96084b1

Please sign in to comment.