addition

package module
v0.0.0-...-5d03f69 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2019 License: MIT Imports: 11 Imported by: 8

README

Directory

bulrush-addition

Provides the ability to expose default interfaces based on database-driven wrappers

mgo addition

Create mgoext
var MGOExt = mgoext.New(conf.Cfg)
Use as a bulrush plugin
app.PostUse(addition.MGOExt)
Defined model and custom your own config if you need
type User struct {
	Base     `bson:",inline"`
	Name     string          `bson:"name" form:"name" json:"name" xml:"name"`
	Password string          `bson:"password" form:"password" json:"password" xml:"password" `
	Age      int             `bson:"age" form:"age" json:"age" xml:"age"`
	Roles    []bson.ObjectId `ref:"role" bson:"roles" form:"roles" json:"roles" xml:"roles" `
}

var _ = addition.MGOExt.Register(&mgoext.Profile{
	DB:        "test",
	Name:      "user",
	Reflector: &User{},
	AutoHook:   true,     // all hook never to added to router, should by hand
})

// RegisterUser inject function
func RegisterUser(r *gin.RouterGroup) {
	addition.MGOExt.API.List(r, "user").Pre(func(c *gin.Context) {
		addition.Logger.Info("before")
	}).Post(func(c *gin.Context) {
		addition.Logger.Info("after")
	}).Auth(func(c *gin.Context) bool {
		return true
	})
	addition.MGOExt.API.Feature("feature").List(r, "user")
	addition.MGOExt.API.One(r, "user")
	addition.MGOExt.API.Create(r, "user")
	addition.MGOExt.API.Update(r, "user")
	addition.MGOExt.API.Delete(r, "user")
}
Defined your config
Configure the priority levels
	Global < Profile < Code
Global
var MGOExt = mgoext.
New().
Init(func(ext *mgoext.Mongo) {
	cfg := &mgo.DialInfo{}
	if err := conf.Conf.Unmarshal("mongo", cfg); err != nil {
		panic(err)
	}
	ext.Conf(cfg)
	ext.API.Opts.Prefix = "/template/mgo"
	ext.API.Opts.RouteHooks = &mgoext.RouteHooks{
		List: &mgoext.ListHook{
			Pre: func(c *gin.Context) {
				Logger.Info("all mgo before")
			},
		},
	}
})
Profile
var _ = addition.MGOExt.Register(&mgoext.Profile{
	Name:      "User",
	Reflector: &User{},
	AutoHook:   true,
	Opts: &mgoext.Opts{
		RouteHooks: &mgoext.RouteHooks{
			List: &mgoext.ListHook{
				Pre: func(c *gin.Context) {
					addition.Logger.Info("user before")
				},
			},
		},
	},
}).Init(func(ext *mgoext.Mongo) {
	Model := addition.MGOExt.Model("User")
	for _, key := range []string{"name"} {
		index := mgo.Index{
			Key:    []string{key},
			Unique: true,
		}
		if err := Model.EnsureIndex(index); err != nil {
			addition.Logger.Error(err.Error())
		}
	}
})
Code
func RegisterUser(r *gin.RouterGroup, role *role.Role) {
	addition.MGOExt.API.List(r, "User").Pre(func(c *gin.Context) {
		addition.Logger.Info("after")
	}).Auth(func(c *gin.Context) bool {
		return true
	})
	addition.MGOExt.API.Feature("feature").List(r, "User")
	addition.MGOExt.API.One(r, "User", role.Can("r1,r2@p1,p3,p4;r4"))
	addition.MGOExt.API.Create(r, "User")
	addition.MGOExt.API.Update(r, "User")
	addition.MGOExt.API.Delete(r, "User")
}

gorm addition

Create gormext
var GORMExt = gormext.New(gormConf)
var _ = GORMExt.Init(func(ext *gormext.GORM) {
	ext.DB.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4")
	ext.API.Opts.Prefix = "/template/gorm"
	ext.API.Opts.RouteHooks = &gormext.RouteHooks{
		List: &gormext.ListHook{
			Pre: func(c *gin.Context) {
				Logger.Info("all gormext before")
			},
		},
	}
})
Use as a bulrush plugin
app.PostUse(addition.GORMExt)
type User struct {
	Base
	Name string `form:"name" json:"name" xml:"name"`
	Age  uint   `form:"age" json:"age" xml:"age"`
}

var _ = addition.GORMExt.Register(&gormext.Profile{
	DB:        "test",
	Name:      "user",
	Reflector: &User{},
	AutoHook:   true,
})
Defined model and custom your own config if you need
// RegisterUser inject function
func RegisterUser(r *gin.RouterGroup) {
	addition.GORMExt.API.List(r, "user").Pre(func(c *gin.Context) {
		addition.Logger.Info("before")
	}).Post(func(c *gin.Context) {
		addition.Logger.Info("after")
	}).Auth(func(c *gin.Context) bool {
		return true
	})
	addition.GORMExt.API.Feature("subUser").List(r, "user")
	addition.GORMExt.API.One(r, "user")
	addition.GORMExt.API.Create(r, "user")
	addition.GORMExt.API.Update(r, "user")
	addition.GORMExt.API.Delete(r, "user")
}
Defined your config
Configure the priority levels
	Global < Profile < Code
Global
var GORMExt = gormext.
New().
Init(func(ext *gormext.GORM) {
	cfg := &gormext.Config{}
	if err := conf.Conf.Unmarshal("sql", cfg); err != nil {
		panic(err)
	}
	ext.Conf(cfg)
	// 建议在数据库创建时指定CHARSET, 这里设置后看gorm log并不起效
	ext.DB.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8")
	ext.DB.LogMode(true)
	ext.API.Opts.Prefix = "/template/gorm"
	ext.API.Opts.RouteHooks = &gormext.RouteHooks{
		// only list creator data
		List: &gormext.ListHook{
			Cond: func(cond map[string]interface{},
				c *gin.Context,
				info struct{ Name string }) map[string]interface{} {
				iden, _ := c.Get("identify")
				if iden != nil {
					token := iden.(*identify.Token)
					cond["CreatorID"] = token.Extra.(map[string]interface{})["ID"]
				}
				return cond
			},
		},
		// only list creator data
		One: &gormext.OneHook{
			Cond: func(cond map[string]interface{},
				c *gin.Context,
				info struct{ Name string }) map[string]interface{} {
				iden, _ := c.Get("identify")
				if iden != nil {
					token := iden.(*identify.Token)
					cond["CreatorID"] = token.Extra.(map[string]interface{})["ID"]
				}
				return cond
			},
		},
		// only update creator data
		Update: &gormext.UpdateHook{
			Cond: func(cond map[string]interface{},
				c *gin.Context,
				info struct{ Name string }) map[string]interface{} {
				iden, _ := c.Get("identify")
				if iden != nil {
					token := iden.(*identify.Token)
					cond["CreatorID"] = token.Extra.(map[string]interface{})["ID"]
				}
				return cond
			},
		},
		// only delete creator data
		Delete: &gormext.DeleteHook{
			Cond: func(cond map[string]interface{},
				c *gin.Context,
				info struct{ Name string }) map[string]interface{} {
				iden, _ := c.Get("identify")
				if iden != nil {
					token := iden.(*identify.Token)
					cond["CreatorID"] = token.Extra.(map[string]interface{})["ID"]
				}
				return cond
			},
		},
	}
})
Profile
var _ = addition.GORMExt.Register(&gormext.Profile{
	Name:      "User",
	Reflector: &User{},
	AutoHook:   true,
	Opts: &gormext.Opts{
		RouteHooks: &gormext.RouteHooks{
			List: &gormext.ListHook{
				Pre: func(c *gin.Context) {
					addition.Logger.Info("User model pre hook")
				},
			},
		},
	},
})
Code
addition.GORMExt.API.List(r, "User").Post(func(c *gin.Context) {
	addition.Logger.Info("after")
}).Auth(func(c *gin.Context) bool {
	return true
}).RouteHooks(&gormext.RouteHooks{
	// Override global config, never query only by own
	List: &gormext.ListHook{
		Cond: func(cond map[string]interface{},
			c *gin.Context,
			info struct{ Name string }) map[string]interface{} {
			return cond
		},
	},
})
SQL translation
指令 是否安全 Example SQL
$eq { "$or": [ { "ID": 117 }, { "Name": "测试2" } ] } ((((id = 117 and deleted_at is null) or (name = '测试2' and deleted_at is null))))
$ne { "$or": [ { "ID": 117 }, { "Name": "测试2" } ] } ((((id = 117 and deleted_at is null) or (name = '测试2' and deleted_at is null))))
$gte { "$or": [ { "ID": 117 }, { "Name": "测试2" } ] } ((((id = 117 and deleted_at is null) or (name = '测试2' and deleted_at is null))))
$gt { "$or": [ { "ID": 117 }, { "Name": "测试2" } ] } ((((id = 117 and deleted_at is null) or (name = '测试2' and deleted_at is null))))
$lte { "$or": [ { "ID": 117 }, { "Name": "测试2" } ] } ((((id = 117 and deleted_at is null) or (name = '测试2' and deleted_at is null))))
$in { "$or": [ { "ID": 117 }, { "Name": "测试2" } ] } ((((id = 117 and deleted_at is null) or (name = '测试2' and deleted_at is null))))
$regex { "$or": [ { "ID": 117 }, { "Name": "测试2" } ] } ((((id = 117 and deleted_at is null) or (name = '测试2' and deleted_at is null))))
$like { "$or": [ { "ID": 117 }, { "Name": "测试2" } ] } ((((id = 117 and deleted_at is null) or (name = '测试2' and deleted_at is null))))
$exists { "$or": [ { "ID": 117 }, { "Name": "测试2" } ] } ((((id = 117 and deleted_at is null) or (name = '测试2' and deleted_at is null))))

Logger

Add Transport
var Logger = addition.RushLogger.
	AddTransports(
		&logger.Transport{
			Dirname: path.Join(path.Join(".", conf.Cfg.Log.Path), "error"),
			Level:   logger.ERROR,
			Maxsize: logger.Maxsize,
		},
		&logger.Transport{
			Dirname: path.Join(path.Join(".", conf.Cfg.Log.Path), "combined"),
			Level:   logger.SILLY,
			Maxsize: logger.Maxsize,
		},
	).
	Init(func(j *logger.Journal) {
		j.SetFlags((logger.LstdFlags | logger.Llongfile))
	})

bulrush logger

Redis

redis := redis.New(conf.Cfg)
rules := []limit.Rule{
	limit.Rule{
		Methods: []string{"GET"},
		Match:   "/api/v1/user*",
		Rate:    1,
	},
	limit.Rule{
		Methods: []string{"GET"},
		Match:   "/api/v1/role*",
		Rate:    2,
	},
}
app.Use(&limit.Limit{
	Frequency: &limit.Frequency{
		Passages: []string{},
		Rules: rules,
		Model: &limit.RedisModel{
			Redis: redis,
		},
	},
})

Apidoc

Install apidoc
npm install apidoc -g
Add ignore to .igonre file
/doc/*
!/doc/api_data.js
!/doc/api_project.js
Generate apidoc
apidoc
apidoc will generate doc dir and some files in doc dir
Use apidoc plugin
// APIDoc defined http rest api
// APIDoc defined http rest api
var APIDoc = apidoc.New()
var _ = APIDoc.
	Config(path.Join("", "doc")).
	Init(func(ctx *apidoc.APIDoc) {
		ctx.Prefix = "/docs"
	})
app.Use(APIDoc)

bulrush apidoc

MIT License

Copyright (c) 2018-2020 Double

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

View Source
const (
	// EventSysBulrushPluginI18NInit defined running event
	EventSysBulrushPluginI18NInit = "EventSysBulrushPluginI18NInit"
)

Variables

RushLogger for app logger

Functions

func CopyMap

func CopyMap(src map[string]interface{}, dest interface{}) error

CopyMap -

func CreateObject

func CreateObject(target interface{}) interface{}

CreateObject reflect and create

func CreateSlice

func CreateSlice(target interface{}) interface{}

CreateSlice reflect and create

func Find

func Find(arrs []interface{}, matcher func(interface{}) bool) interface{}

Find elements

func LeftOkV

func LeftOkV(left interface{}, right ...bool) interface{}

LeftOkV -

func LeftSV

func LeftSV(left interface{}, right error) interface{}

LeftSV -

func LeftV

func LeftV(left interface{}, right interface{}) interface{}

LeftV -

func MysqlRealEscapeString

func MysqlRealEscapeString(value string) string

MysqlRealEscapeString defined sql word replace

func RandString

func RandString(n int) string

RandString -

func RightV

func RightV(left interface{}, right interface{}) interface{}

RightV -

func Some

func Some(target interface{}, initValue interface{}) interface{}

Some get or a default value

func ToIntArray

func ToIntArray(t []interface{}) []int

ToIntArray -

func ToStrArray

func ToStrArray(t []interface{}) []string

ToStrArray -

Types

type I18N

type I18N struct {
	Prefix string
	// contains filtered or unexported fields
}

I18N defined I18N plugin

func NewI18N

func NewI18N() *I18N

NewI18N defined NewI18N plugin

func (*I18N) AddLocale

func (i18n *I18N) AddLocale(locale string, kv map[string]interface{}) *I18N

AddLocale defined AddLocale func

func (*I18N) AddLocales

func (i18n *I18N) AddLocales(locales M) *I18N

AddLocales defined AddLocales func

func (*I18N) BuildI18nKey

func (i18n *I18N) BuildI18nKey(mod string, str string) string

BuildI18nKey defined BuildI18nKey func

func (*I18N) GetLocale

func (i18n *I18N) GetLocale(locale string) interface{}

GetLocale defined GetLocale func

func (*I18N) I18NLocale

func (i18n *I18N) I18NLocale(locale string, init string) string

I18NLocale defined I18NLocale func

func (*I18N) Init

func (i18n *I18N) Init(init func(*I18N) func()) *I18N

Init i18n

func (*I18N) InitLocal

func (i18n *I18N) InitLocal(init func(*I18N)) *I18N

InitLocal defined InitLocal func

func (*I18N) Plugin

func (i18n *I18N) Plugin(event events.EventEmmiter, httpProxy *gin.Engine, router *gin.RouterGroup) *I18N

Plugin defined Plugin func

func (*I18N) Pre

func (i18n *I18N) Pre()

Pre defined Pre func

func (*I18N) SetCtxLocal

func (i18n *I18N) SetCtxLocal(ctxLocal func(c *gin.Context) string) *I18N

SetCtxLocal defined SetCtxLocal func

type M

type M map[string]interface{}

M defiend map

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL