trinity

package module
v1.13.1 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2020 License: MIT Imports: 52 Imported by: 0

README

trinity

Build Status GitHub Actions codecov Go Report Card GoDoc Release

golang restframework plugin with gin+gorm, 5 lines to generate rest api with high security
p.s: django restframework like :)

特性

  • 集成gorm
  • 集成gin
  • 快速注册路由
  • 链路追踪,返回错误代码行数,及sql
  • 快速migrate表并生成权限
  • 支持快速开发rest风格api并实现增删改查,开箱即用
  • JWT token生成,认证,刷新中间件
  • json log风格中间件
  • 支持请求事务
  • 支持自定义用户权限查询
  • 支持自定义接口访问权限
  • 支持自定义接口数据访问权限
  • 自定义分页
  • 自定义过滤查询
  • 自定义搜索
  • 自定义预加载(gorm preload)
  • 自定义排序
  • 自定义查询包含字段
  • 自定义http方法重写
  • 添加了change log

安装

打开终端输入

$ go get -u github.com/PolarPanda611/trinity

done.

文档


// ViewSetCfg for viewset config
type ViewSetCfg struct {
	sync.RWMutex
	// global config
	Db *gorm.DB
	// HasAuthCtl
	// if do the auth check ,default false
	HasAuthCtl bool
	// AuthenticationBackendMap
	// if HasAuthCtl == false ; pass... customize the authentication check , default jwt  ;
	// please set UserID in context
	// e.g : c.Set("UserID", tokenClaims.UID)
	AuthenticationBackendMap map[string]func(c *gin.Context) error
	// GetCurrentUserAuth
	// must be type : func(c *gin.Context, db *gorm.DB) error
	// if HasAuthCtl == false ; pass...
	// get user auth func with UserID if you set in AuthenticationBackend
	// please set UserPermission and UserKey in context
	// e.g : c.Set("UserKey",UserKey) with c.GetString("UserID")
	// e.g : c.Set("UserPermission", UserPermission) with c.GetString("UserID")
	GetCurrentUserAuth interface{}
	// AccessBackendReqMap
	// if HasAuthCtl == false ; pass... customize the access require permission
	AccessBackendRequireMap map[string][]string
	// AccessBackendCheckMap
	// if HasAuthCtl == false ; pass... customize the access check , check user permission
	// e.g : userPermission :=  c.GetString("UserPermission")
	// e.g : requiredPermission := []string{"123"} get with AccessBackendReqMap by default
	// e.g : trinity.CheckAccessAuthorization(requiredPermission , userPermission) , true?allow:deny
	AccessBackendCheckMap map[string]func(v *ViewSetRunTime) error
	// PreloadListMap gorm preload list
	PreloadListMap map[string]map[string]func(db *gorm.DB) *gorm.DB
	// FilterBackendMap : all the query will with this filter backend
	FilterBackendMap map[string]func(c *gin.Context, db *gorm.DB) *gorm.DB
	// FilterByList : only in FilterByList will do the filter
	FilterByList []string
	// FilterCustomizeFunc : can do the customize filter ,mapping with FilterByList
	FilterCustomizeFunc map[string]func(db *gorm.DB, queryValue string) *gorm.DB
	// SearchingByList : with keyword "SearchBy" on url query ,
	// will do the where (xxx =? or xxx=?)
	SearchingByList []string
	// OrderingByList : with keyword "OrderBy" on url query ,
	// only define in OrderingByList will do the order by
	// e.g: OrderBy=xxx-   ==> order by xxx desc
	// e.g: OrderBy=xxx   ==> order by xxx asc
	OrderingByList map[string]bool
	// PageSize default 10
	// keyword : PageNum , PageSize to do the limit and offset
	PageSize int
	// Retrieve: customize retrieve func
	Retrieve func(r *ViewSetRunTime) *ViewSetRunTime
	// Get: customize Get func
	Get func(r *ViewSetRunTime) *ViewSetRunTime
	// Post: customize Post func
	Post func(r *ViewSetRunTime) *ViewSetRunTime
	// Put: customize Put func
	Put func(r *ViewSetRunTime) *ViewSetRunTime
	// Patch: customize Patch func
	Patch func(r *ViewSetRunTime) *ViewSetRunTime
	// Delete: customize Delete func
	Delete func(r *ViewSetRunTime) *ViewSetRunTime
}

例子

  • 准备条件,建立model
//Country model Country
type Country struct {
	Model
	Code        string `json:"code" gorm:"type:varchar(50);index;unique;not null;"`
	Name        string `json:"name" gorm:"type:varchar(50);"`
	Description string `json:"description" gorm:"type:varchar(100);index;"`
}

*初始化trinity设置

// GlobalViewSet global view set config by default value
var GlobalViewSet *trinity.ViewSetCfg


//Inittrinity get default setting
func Inittrinity() {
	trinity.Jwtexpirehour = setting.Cfg.Jwt.Jwtexpirehour
	// Jwtheaderprefix for jwt
	trinity.Jwtheaderprefix = setting.Cfg.Jwt.Jwtheaderprefix
	// Secretkey for jwt
	trinity.Secretkey = setting.Cfg.Secretkey
	// Jwtissuer for jwt
	trinity.Jwtissuer = setting.Cfg.Jwt.Jwtissuer

	GlobalViewSet = trinity.InitDefault(db.Dsource)

	// 在此覆盖默认全局设置
	GlobalViewSet.PageSize = setting.Cfg.Pagesize
}

  • 使用log,jwt中间件及注册路由
func Router() *gin.Engine {
    r := gin.New()
    ````
    r.Use(trinity.JWT())                 // jwt中间件
    r.Use(trinity.LoggerWithFormatter()) // log中间件,链路追踪需开启log中间件,获取TraceID *gin.Context.GetString("TraceID")
    v1 := r.Group("/api/v1")
    {
        // register RESTFUL API router by resouce name
	/*
	*@param RouterGroup :  the router group you want to register
	*@param Resource : the resource of the REST API
	*@param ViewSet : the service of the REST API
	*@param SupportedMethod : the service list of the REST API
	 */
	 // same as 
	 //r.GET("/"+resource+"/:key", viewset)
	 //r.GET("/"+resource, viewset)
	 //r.POST("/"+resource, viewset)
	 //r.PATCH("/"+resource+"/:key", viewset)
	 //r.PUT("/"+resource+"/:key", viewset)
	 //r.DELETE("/"+resource+"/:key", viewset)
        trinity.RegisterRestStyleRouter(v1, "users", servicev1.UserViewSet, []string{"Retrieve", "List", "Create", "Update", "Delete"})
    }
    ```
  • 注册路由处理
// CountryViewSet hanlde router
func CountryViewSet(c *gin.Context) {
	v := trinityinit.GlobalViewSet.New()
	// 在此覆盖默认局部设置
	v.HasAuthCtl = true
	v.FilterByList = []string{"trace_id"}
	// v.GetCurrentUserAuth = func(c *gin.Context, db *gorm.DB) error {
	// 	c.Set("UserPermission", []string{"system.view.Country"})
	// 	return nil
	// }
	utils.HandleResponse(v.NewRunTime(
		c,
		&model.Country{},
		&model.Country{},
		&[]model.Country{},
	).ViewSetServe())
}
  • 支持快速生成过滤

    • 过滤 (系统预置关键字) -关键字列表[]string{"like", "ilike", "in", "notin", "start", "end", "lt", "lte", "gt", "gte", "isnull", "isempty"} -支持关联关系过滤,以双下划线"__"分隔
	// Example :table user(id , name , dpp_id) table dpp {id , code , country_id}, table country {id , name ,create_time}
	// GET : http://127.0.0.1/countries?name__ilike=PolarPanda611&dpp__country_name__ilike=China&dpp__country__create_time__start=2019-01-01
	// ----FilterByList   filter condition must configured in FilterByList config  
	// SETTING : v.FilterByList=[]string{"name__ilike","dpp__country_name__ilike","dpp__country__create_time__start"}
	// EXECUTE:
	// name__ilike ==> name ilike '%PolarPanda611%'  
	// dpp__country__name__ilike => dpp_id in (select id from dpp where country_id in (select id from country where name ilike '%China%' ))
	// dpp__country__create_time__start => dpp_id in (select id from dpp where country_id in (select id from country where create_time > '2019-01-01 00:00:00' ))

	xxx__like=ooo 		=> xxx like '%ooo%'  
	xxx__ilike=ooo 		=> xxx like '%ooo%'  caps no sensitive
	xxx__in=aaa,bbb,ccc => xxx in ['aaa','bbb','ccc']  
	xxx__start=date1	=> xxx > 'date1 00:00:00'  
	xxx__end=date2		=> xxx < 'date2 23:59:59'  
	xxx__isnull=true 	=> xxx is null 
	xxx__isnull=false 	=> xxx is not null 
	xxx__isempty=true	=> (COALESCE("xxx"::varchar ,'') ='' )  
	xxx__isempty=false	=> (COALESCE("xxx"::varchar ,'') !='' )  
	xxx=ooo				=> xxx = ooo
  • 自定义过滤 (自定义关键字和查询方法)
	#Example  :http://127.0.0.1/countries?CustomizeFilterUser=PolarPanda611
	----FilterByList   filter condition must configured in FilterByList config  
	// v.FilterByList=[]string{"CustomizeFilterUser"}
	// v.FilterCustomizeFunc=map[string]func(db *gorm.DB, queryValue string) *gorm.DB{
	//		"CustomizeFilterUser":func(db *gorm.DB, queryValue string) *gorm.DB{
	//			db.Where("name = ?" , "PolarPanda611")
	//		}
	// }

	CustomizeFilterUser=PolarPanda611	=> name = 'PolarPanda611'  
	
  • 自定义搜索 (自定义关键字集合)
	#Example  :http://127.0.0.1/countries?SearchBy=xxx
	----SearchingByList   search condition must configured in in SearchingByList config  
	//v.SearchingByList=[]string{"name","address"}
	SearchBy=xxx		=>(name ilike '%xxx%' or address ilike '%xxx%')  
  • 自定义排序 (自定义排序关键字)
	#Example  :http://127.0.0.1/countries?OrderingBy=-id,name
	----OrderingByList  order by condition must configured in in OrderingByList config  
	OrderingBy=-id,name	=> order by id desc , name    
  • 自定义预加载 (自定义预加载)
	
// QuotationViewSet hanlde router
	func QuotationViewSet(c *gin.Context) {
		v := trinity.NewViewSet()
		v.HasAuthCtl = true
		v.PreloadListMap = map[string]map[string]func(db *gorm.DB) *gorm.DB{
			"RETRIEVE": map[string]func(db *gorm.DB) *gorm.DB{
				"Details":               nil,
				// "Details": func(db *gorm.DB) *gorm.DB {
				// 	return db.Where("id=1 ")
				// },
			},
			"GET": nil,
		}
		v.EnableChangeLog = true
		v.PostValidation = &QuotationPostValidation{}
		v.NewRunTime(
			c,
			&model.Quotation{},
			&model.Quotation{},
			&[]model.Quotation{},
		).ViewSetServe()
	}
  • 自定义分页 (自定义分页数量和页码)
	//默认开启分页
	#Example  :http://127.0.0.1/countries?PageSize=44&PageNum=2
	----queryByPagination By default , the list will be paged , default page size is configured in Pagination config  
	//offset := PageNumFieldInt * PageSizeFieldInt -1 
	//limit := PageSizeFieldInt  
	PageNum=1		=>PageNum= (1,2.....)  
	PageSize=10		=>PageSize= default value:10
	PaginationOn		=>by default :true , will open the pagination , if else , close the pagination, return all the list 
	//关闭分页
	#Example  :http://127.0.0.1/countries?PaginationOn=false
  • 自定义请求回复

// ResponseData http response
type ResponseData struct {
	Status  int         // the http response status  to return
	Result  interface{} // the response data  if req success
	TraceID string
}

// Response handle trinity return value
func Response(r *ViewSetRunTime) {
	var res ResponseData
	res.Status = r.Status
	res.TraceID = r.Gcontext.GetString("TraceID")
	if r.RealError != nil {
		r.Cfg.Logger.LogWriter(r)
		r.Gcontext.Error(r.RealError)
		r.Gcontext.Error(r.UserError)
		res.Result = r.UserError.Error()
		r.Gcontext.AbortWithStatusJSON(r.Status, res)
	} else {
		res.Result = r.ResBody
		r.Gcontext.JSON(r.Status, res)
	}
	return

}
  • 支持请求事务 整个request将会被同一个事物包裹, -如果返回err,则会request整体roll back -如果不返回err,则会request整体commit
	local:
		webapp:
			...
			atomicrequest: true
  • 添加change log 目前不支持嵌套map添加change log
	migrate  		&trinity.AppChangelog{}, 

	在viewset中
	// PartsViewSet hanlde router
	func PartsViewSet(c *gin.Context) {

		v := trinity.NewViewSet()
		v.HasAuthCtl = true
		v.EnableChangeLog = true
		v.NewRunTime(
			c,
			&model.Part{},
			&model.Part{},
			&[]model.Part{},
		).ViewSetServe()
	}

to do list :

支持字段级验证请求数据
外键字段过滤

post and patch not support assosiation update and create

Documentation

Index

Constants

View Source
const DefaultGRPCHealthCheck string = "/grpc.health.v1.Health/Check"

DefaultGRPCHealthCheck default grpc health check name

View Source
const GRPCMethodKey string = "method"

GRPCMethodKey used in passing grpc value

View Source
const RFC3339FullDate = "2006-01-02"

RFC3339FullDate for rfc full date

View Source
const ReqUserNameKey string = "req_user_name"

ReqUserNameKey used in passing grpc value

View Source
const TraceIDKey string = "trace_id"

TraceIDKey used in passing grpc value

Variables

View Source
var (

	// ErrTokenExpired return token expired err
	ErrTokenExpired = errors.New("app.err.TokenExpired")
	// ErrTokenWrongIssuer return wrong issuer err
	ErrTokenWrongIssuer = errors.New("app.err.TokenWrongIssuer")
	// ErrTokenWrongHeaderPrefix return wrong header prefix
	ErrTokenWrongHeaderPrefix = errors.New("app.err.TokenWrongHeaderPrefix")
	// ErrTokenWrongAuthorization return wrong authorization
	ErrTokenWrongAuthorization = errors.New("app.err.TokenWrongAuthorization")

	// ErrUnverifiedToken unverified token
	ErrUnverifiedToken = errors.New("app.err.UnverifiedToken")
	// ErrGeneratedToken GenerateTokenFailed
	ErrGeneratedToken = errors.New("app.err.GenerateTokenFailed")
	// ErrGetUserAuth wrong get user auth func
	ErrGetUserAuth = errors.New("app.err.WrongGetUserAuthFunc")
	// ErrAccessAuthCheckFailed fail to pass access auth check
	ErrAccessAuthCheckFailed = errors.New("app.error.AccessAuthorizationCheckFailed")
	// ErrLoadDataFailed app.error.LoadDataFailed
	ErrLoadDataFailed = errors.New("app.error.LoadDataFailed")
	// ErrResolveDataFailed app.error.ResolveDataFailed
	ErrResolveDataFailed = errors.New("app.error.ResolveDataFailed")
	// ErrCreateDataFailed app.error.CreateDataFailed
	ErrCreateDataFailed = errors.New("app.error.CreateDataFailed")
	// ErrUpdateDataFailed app.error.UpdateDataFailed
	ErrUpdateDataFailed = errors.New("app.error.UpdateDataFailed")
	// ErrDeleteDataFailed app.error.DeleteDataFailed
	ErrDeleteDataFailed = errors.New("app.error.DeleteDataFailed")
	// ErrUnknownService  app.error.UnknownService
	ErrUnknownService = errors.New("app.error.UnknownService")
	// ErrDataAssertion  app.error.DataAssetion
	ErrDataAssertion = errors.New("app.error.DataAssetion")
	// ErrUpdateZeroAffected  app.error.DataAssetion
	ErrUpdateZeroAffected = errors.New("app.error.ErrUpdateZeroAffected")
)
View Source
var (
	// ErrClosed is the error when the client pool is closed
	ErrClosed = errors.New("grpc pool: client pool is closed")
	// ErrTimeout is the error when the client pool timed out
	ErrTimeout = errors.New("grpc pool: client pool timed out")
	// ErrAlreadyClosed is the error when the client conn was already closed
	ErrAlreadyClosed = errors.New("grpc pool: the connection was already closed")
	// ErrFullPool is the error when the pool is already full
	ErrFullPool = errors.New("grpc pool: closing a ClientConn into a full pool")
)

Functions

func CheckAccessAuthorization

func CheckAccessAuthorization(requiredPermission, userPermission []string) error

CheckAccessAuthorization to check access authorization

func CheckFileIsExist added in v0.0.3

func CheckFileIsExist(filename string) bool

CheckFileIsExist : check file if exist ,exist -> true , not exist -> false , *

  • @param filename string ,the file name need to check
  • @return boolean string

func ConsulResolverInit added in v1.1.7

func ConsulResolverInit(address string, serviceName string) error

ConsulResolverInit init coonsul

func DataVersionFilter added in v0.0.33

func DataVersionFilter(param interface{}, isCheck bool) func(db *gorm.DB) *gorm.DB

DataVersionFilter filter key by param

func DbLoggerFormatter added in v0.0.3

func DbLoggerFormatter(r *ViewSetRunTime, v ...interface{}) string

DbLoggerFormatter for db execute logger

func DefaultAccessBackend

func DefaultAccessBackend(v *ViewSetRunTime) error

DefaultAccessBackend for Mixin

func DefaultDeleteCallback added in v0.0.40

func DefaultDeleteCallback(r *ViewSetRunTime)

DefaultDeleteCallback default delete callback

func DefaultFilterBackend

func DefaultFilterBackend(c *gin.Context, db *gorm.DB) *gorm.DB

DefaultFilterBackend for Mixin

func DefaultGetCallback added in v0.0.40

func DefaultGetCallback(r *ViewSetRunTime)

DefaultGetCallback Default GetHandler

func DefaultPatchCallback added in v0.0.40

func DefaultPatchCallback(r *ViewSetRunTime)

DefaultPatchCallback : PATCH method

func DefaultPostCallback added in v0.0.40

func DefaultPostCallback(r *ViewSetRunTime)

DefaultPostCallback : Create method

func DefaultPutCallback added in v0.0.40

func DefaultPutCallback(r *ViewSetRunTime)

DefaultPutCallback : PATCH method

func DefaultRetrieveCallback added in v0.0.40

func DefaultRetrieveCallback(r *ViewSetRunTime)

DefaultRetrieveCallback : Retrieve method

func DeleteExtraSpace added in v0.0.40

func DeleteExtraSpace(s string) string

DeleteExtraSpace remove extra space

func DeleteHandler added in v0.0.40

func DeleteHandler(r *DeleteMixin)

DeleteHandler : DELETE method

func FilterByCustomizeCondition added in v0.0.37

func FilterByCustomizeCondition(ok bool, k string, v ...interface{}) func(db *gorm.DB) *gorm.DB

FilterByCustomizeCondition filter by customize condition

func FilterByFilter

func FilterByFilter(c *gin.Context, FilterByList []string, FilterCustomizeFunc map[string]func(db *gorm.DB, queryValue string) *gorm.DB) func(db *gorm.DB) *gorm.DB

FilterByFilter handle filter

func FilterByParam

func FilterByParam(param int64) func(db *gorm.DB) *gorm.DB

FilterByParam to filter by param return db

func FilterBySearch

func FilterBySearch(c *gin.Context, SearchingByList []string) func(db *gorm.DB) *gorm.DB

FilterBySearch handle search

func GenerateSnowFlakeID added in v0.0.33

func GenerateSnowFlakeID(nodenumber int64) int64

GenerateSnowFlakeID generate snowflake id

func GenerateToken

func GenerateToken(userkey string) (string, error, error)

GenerateToken generate tokens used for auth

func GetCurrentTime added in v0.0.40

func GetCurrentTime() time.Time

GetCurrentTime get current time

func GetCurrentTimeString added in v0.0.40

func GetCurrentTimeString(timeType string) string

GetCurrentTimeString get current time with string

func GetCurrentTimeUnix added in v0.0.40

func GetCurrentTimeUnix() int64

GetCurrentTimeUnix get current time with unix time

func GetFreePort added in v1.1.7

func GetFreePort() (int, error)

GetFreePort get one free port

func GetHandler added in v0.0.40

func GetHandler(r *GetMixin)

GetHandler : List method

func GetRequestType

func GetRequestType(c *gin.Context) string

GetRequestType to get http request type with restful style

func GetServiceID added in v1.1.7

func GetServiceID(projectName string, projectVersion string, ServiceIP string, ServicePort int) string

GetServiceID get service name which will register to service mesh

func GetServiceName added in v1.1.7

func GetServiceName(projectName string) string

GetServiceName get service name which will register to service mesh

func GetTypeName

func GetTypeName(myvar interface{}, isToLowerCase bool) string

GetTypeName to get struct type name

func Getparentdirectory

func Getparentdirectory(path string, level int) string

Getparentdirectory : get parent directory of the path ,

  • @param path string ,the path you want to get parent directory
  • @return string , the parent directory you need

func HandleBackend added in v0.0.37

func HandleBackend(c *gin.Context, backend func(c *gin.Context, db *gorm.DB) *gorm.DB) func(db *gorm.DB) *gorm.DB

HandleBackend handle filter backend

func HandleFilterBackend

func HandleFilterBackend(v *ViewSetCfg, method string, c *gin.Context) func(db *gorm.DB) *gorm.DB

HandleFilterBackend handle filter backend

func HandlestructBySelect

func HandlestructBySelect(c *gin.Context, resource interface{}) (int, interface{}, error)

HandlestructBySelect handling select

func InSlice

func InSlice(value string, stringSlice []string) bool

InSlice if value in stringlist

func IsFuncInited added in v0.0.40

func IsFuncInited(function MixinCallback) bool

IsFuncInited : is function inited : true inited function , false not inited or not a function

func JWTMiddleWare added in v0.0.40

func JWTMiddleWare() gin.HandlerFunc

JWTMiddleWare is jwt middleware

func JwtAuthBackend

func JwtAuthBackend(c *gin.Context) (error, error)

JwtAuthBackend check authorization header token is valid

func JwtUnverifiedAuthBackend

func JwtUnverifiedAuthBackend(c *gin.Context) error

JwtUnverifiedAuthBackend get claim info

func LoadConfigError added in v0.0.25

func LoadConfigError(err error)

LoadConfigError load config error log fatal

func LoadCustomizeSetting added in v1.1.12

func LoadCustomizeSetting(customizeSettingSlice ...CustomizeSetting)

LoadCustomizeSetting used for load trinity config file by default and customize setting if necessery

func LogMiddleware added in v0.0.40

func LogMiddleware() gin.HandlerFunc

LogMiddleware gin log formatter

func LogPrint added in v0.0.4

func LogPrint(v ...interface{})

LogPrint customize log

func LoggingInterceptor added in v1.1.7

func LoggingInterceptor(log Logger, setting ISetting) func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)

LoggingInterceptor record log

func NewAPIInGroup

func NewAPIInGroup(rg *gin.RouterGroup, resource string, viewset gin.HandlerFunc, SupportedMethod []string)

NewAPIInGroup register new api in group

func NewEtcdClientConn added in v1.1.8

func NewEtcdClientConn(address string, port int, serviceName string) (*grpc.ClientConn, error)

NewEtcdClientConn new etcd client connection

func PatchHandler added in v0.0.40

func PatchHandler(r *PatchMixin)

PatchHandler : List method

func PostHandler added in v0.0.40

func PostHandler(r *PostMixin)

PostHandler : List method

func PutHandler added in v0.0.40

func PutHandler(r *PutMixin)

PutHandler : List method

func QueryByOrdering

func QueryByOrdering(c *gin.Context, EnableOrderBy bool, OrderingByList map[string]bool) func(db *gorm.DB) *gorm.DB

QueryByOrdering handle ordering

func QueryByPagination

func QueryByPagination(c *gin.Context, PageSize int) func(db *gorm.DB) *gorm.DB

QueryByPagination handling pagination

func QueryByPreload

func QueryByPreload(PreloadList map[string]func(db *gorm.DB) *gorm.DB) func(db *gorm.DB) *gorm.DB

QueryByPreload handling preload

func QueryBySelect

func QueryBySelect(c *gin.Context) func(db *gorm.DB) *gorm.DB

QueryBySelect handling select

func RecordErrorLevelTwo

func RecordErrorLevelTwo() (uintptr, string, int)

RecordErrorLevelTwo login error and print line , func , and error to gin context

func RecoveryInterceptor added in v1.1.7

func RecoveryInterceptor(log Logger) func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error)

RecoveryInterceptor recovery from panic

func RetriveHandler added in v0.0.40

func RetriveHandler(r *RetrieveMixin)

RetriveHandler : List method

func RunMigration added in v0.0.8

func RunMigration()

RunMigration func to run the migration scan the migration file under static/migrations

func SetConfigFilePath added in v0.0.26

func SetConfigFilePath(path string)

SetConfigFilePath get rootpath

func SetDefaultWriter added in v1.1.12

func SetDefaultWriter(writer io.Writer)

SetDefaultWriter set default writer for trinity

func SetRunMode added in v0.0.26

func SetRunMode(runmode string)

SetRunMode set RunMode

func SliceInSlice

func SliceInSlice(sliceToCheck []string, slice []string) bool

SliceInSlice if slice in slice

func UserAuthInterceptor added in v1.1.7

func UserAuthInterceptor(log Logger) func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)

UserAuthInterceptor record log

func WrongRunMode added in v0.0.25

func WrongRunMode(runmode string)

WrongRunMode load config error

Types

type AppChangelog added in v0.0.29

type AppChangelog struct {
	Logmodel
	Resource    string `json:"resource"  gorm:"type:varchar(50);not null;default:''"`     // resource name
	ResourceKey string `json:"resource_key"  gorm:"type:varchar(50);not null;default:''"` // resource key
	DVersion    string `json:"d_version" gorm:"type:varchar(50);not null;default:''"`     // current change d version
	Type        string `json:"type"  gorm:"type:varchar(50);not null;default:''"`         // operation type create , update , delete
	Column      string `json:"column"  gorm:"type:varchar(50);not null;default:''"`
	OldValue    string `json:"old_value"  gorm:"type:varchar(200);not null;default:''"` // old value before change
	NewValue    string `json:"new_value"  gorm:"type:varchar(200);not null;default:''"` // new value after change
	TraceID     string `json:"trace_id"  gorm:"type:varchar(50);not null;"`
}

AppChangelog model Error

type AppError

type AppError struct {
	Logmodel
	TraceID  string `json:"trace_id"  gorm:"type:varchar(50);index;not null;"` //http seq number
	File     string `json:"file"  `
	Line     string `json:"line"  gorm:"type:varchar(50);"`
	FuncName string `json:"func_name"`
	Error    string `json:"error" `
}

AppError model Error

func (*AppError) RecordError

func (e *AppError) RecordError()

RecordError to record error

type AutoModel added in v0.0.37

type AutoModel struct {
	ID           int64      `json:"key,string"  gorm:"primary_key;"`
	CreatedTime  *time.Time `json:"created_time" `
	CreateUser   *User      `json:"create_user"`
	CreateUserID int64      `json:"create_user_id,string"`
	UpdatedTime  *time.Time `json:"updated_time" `
	UpdateUser   *User      `json:"update_user"`
	UpdateUserID int64      `json:"update_user_id,string"`
	DeletedTime  *time.Time `json:"deleted_time" `
	DeleteUser   *User      `json:"delete_user"`
	DeleteUserID int64      `json:"delete_user_id,string"`
}

AutoModel with id auto increment

type Claims

type Claims struct {
	Userkey string `json:"userkey"`
	jwt.StandardClaims
}

Claims data to sign

func CheckTokenValid

func CheckTokenValid(c *gin.Context) (*Claims, error, error)

CheckTokenValid check authorization header token is valid

func ParseToken

func ParseToken(token string) (*Claims, error, error)

ParseToken parsing token

type ClientConn added in v1.1.8

type ClientConn struct {
	*grpc.ClientConn
	// contains filtered or unexported fields
}

ClientConn is the wrapper for a grpc client conn

func (*ClientConn) Close added in v1.1.8

func (c *ClientConn) Close() error

Close returns a ClientConn to the pool. It is safe to call multiple time, but will return an error after first time

func (*ClientConn) Unhealthy added in v1.1.8

func (c *ClientConn) Unhealthy()

Unhealthy marks the client conn as unhealthy, so that the connection gets reset when closed

type Context added in v1.1.7

type Context interface {
	GetDB() *gorm.DB
	GetTXDB() *gorm.DB
	GetLogger() Logger
	GetRequest() interface{}
	GetResponse() interface{}
}

Context interface to get Req Context

func NewContext added in v1.1.11

func NewContext(db *gorm.DB, setting ISetting, userRequestsCtx UserRequestsCtx, logger Logger) Context

NewContext new ctx

type ContextImpl added in v1.1.12

type ContextImpl struct {
	// contains filtered or unexported fields
}

ContextImpl context impl

func (*ContextImpl) GetDB added in v1.1.12

func (c *ContextImpl) GetDB() *gorm.DB

GetDB get db instance

func (*ContextImpl) GetLogger added in v1.1.12

func (c *ContextImpl) GetLogger() Logger

GetLogger get current user name

func (*ContextImpl) GetRequest added in v1.1.12

func (c *ContextImpl) GetRequest() interface{}

GetRequest get user request data

func (*ContextImpl) GetResponse added in v1.1.12

func (c *ContextImpl) GetResponse() interface{}

GetResponse get user response data

func (*ContextImpl) GetTXDB added in v1.1.14

func (c *ContextImpl) GetTXDB() *gorm.DB

GetTXDB get db instance with transaction

type CustomizeSetting added in v0.0.25

type CustomizeSetting interface {
	Load(runmode string, configFilePath string)
}

CustomizeSetting for customize setting

type DeleteMixin

type DeleteMixin struct {
	ViewSetRunTime *ViewSetRunTime
}

DeleteMixin for Get request

func (*DeleteMixin) Handler

func (r *DeleteMixin) Handler()

Handler for handle delete request

type Factory added in v1.1.8

type Factory func() (*grpc.ClientConn, error)

Factory is a function type creating a grpc client

type FactoryWithContext added in v1.1.8

type FactoryWithContext func(context.Context) (*grpc.ClientConn, error)

FactoryWithContext is a function type creating a grpc client that accepts the context parameter that could be passed from Get or NewWithContext method.

type FedidClaims

type FedidClaims struct {
	ClientID string `json:"client_id,omitempty"`
	UID      string `json:"uid,omitempty"`
	Origin   string `json:"origin,omitempty"`
	jwt.StandardClaims
}

FedidClaims data to sign

func CheckUnverifiedTokenValid

func CheckUnverifiedTokenValid(c *gin.Context) (*FedidClaims, error)

CheckUnverifiedTokenValid check authorization header token is valid

func ParseUnverifiedToken

func ParseUnverifiedToken(token string) (*FedidClaims, error)

ParseUnverifiedToken parsing token

type FilterQuery added in v0.0.40

type FilterQuery struct {
	QueryName  string
	QueryValue string

	//output
	ConditionSQL string
	ValueSQL     interface{}
	// contains filtered or unexported fields
}

FilterQuery for filter query handling

func (*FilterQuery) GetFilterQuerySQL added in v0.0.40

func (f *FilterQuery) GetFilterQuerySQL()

GetFilterQuerySQL get query

type GRPCMethod added in v1.1.11

type GRPCMethod string

GRPCMethod grpc method

type GetMixin

type GetMixin struct {
	ViewSetRunTime *ViewSetRunTime
}

GetMixin for Get request

func (*GetMixin) Handler

func (r *GetMixin) Handler()

Handler for handle retrieve request

type GlobalSetting added in v0.0.25

type GlobalSetting struct {
	Local   Setting
	Develop Setting
	Preprod Setting
	Master  Setting
}

GlobalSetting : for trinity global setting

type Group

type Group struct {
	Model
	Name        string       `json:"name" gorm:"type:varchar(50);unique;not null;"`
	Description string       `json:"description" gorm:"type:varchar(100);not null;default:''"`
	Permissions []Permission `json:"permissions" gorm:"many2many:group_permissions;"`
	PGroup      *Group       `json:"p_group"`
	PID         int64        `json:"p_id,string"`
	Roles       []Role       `json:"roles" gorm:"many2many:group_roles;"`
}

Group model Group

type ISetting added in v1.1.7

type ISetting interface {
	GetDebug() bool
	GetTLSEnabled() bool
	GetSetting() *Setting
	GetProjectName() string
	GetTags() []string
	GetWebAppType() string
	GetWebAppAddress() string
	GetWebAppPort() int
	GetServiceMeshAddress() string
	GetServiceMeshPort() int
	GetDeregisterAfterCritical() int
	GetHealthCheckInterval() int
	GetCAPemFile() string
	GetServerPemFile() string
	GetServerKeyFile() string
	GetClientPemFile() string
	GetClientKeyFile() string
	GetProjectVersion() string
	GetLogRootPath() string
	GetLogName() string
	GetServiceMeshType() string
	GetServiceMeshAutoRegister() bool
	GetAtomicRequest() bool
	GetTablePrefix() string
	GetWebAppMediaURL() string
	GetWebAppStaticURL() string
	GetWebAppMediaPath() string
	GetWebAppStaticPath() string
	GetCacheSize() int
	GetCacheTimeout() int
	GetPageSize() int
	GetWebAppBaseURL() string
	GetMigrationPath() string
	GetJwtVerifyExpireHour() bool
	GetJwtVerifyIssuer() bool
	GetJwtIssuer() string
	GetJwtHeaderPrefix() string
	GetJwtExpireHour() int
	GetReadTimeoutSecond() int
	GetReadHeaderTimeoutSecond() int
	GetWriteTimeoutSecond() int
	GetIdleTimeoutSecond() int
	GetMaxHeaderBytes() int
	GetSecretKey() string
	GetAllowOrigins() []string
	GetAllowMethods() []string
	GetAllowHeaders() []string
	GetExposeHeaders() []string
	GetAllowCredentials() bool
	GetMaxAgeHour() int
	GetCorsEnable() bool
	GetDBHost() string
	GetDBPort() string
	GetDBUser() string
	GetDBPassword() string
	GetDBName() string
	GetDBOption() string
	GetDBType() string
	GetDbMaxIdleConn() int
	GetDbMaxOpenConn() int
	GetLogEnable() bool
}

ISetting setting interface

type LogFormat

type LogFormat struct {
	Timestamp      string        `json:"@timestamp"` // current timestamp
	Version        string        `json:"@version"`   //
	LoggerName     string        `json:"logger_name"`
	ThreadName     string        `json:"thread_name"`
	Level          string        `json:"level"`
	Hostname       string        `json:"hostname"`
	ModuleName     string        `json:"module_name"`
	TraceID        string        `json:"trace_id"`
	Latency        time.Duration `json:"latency"`
	ClientIP       string        `json:"client_ip"`
	HTTPMethod     string        `json:"http_method"`
	HTTPPath       string        `json:"http_path"`
	HTTPStatusCode int           `json:"http_status_code"`
	Message        string        `json:"message"`      // error message
	ErrorDetail    string        `json:"error_detail"` // error detail info
	BodySize       int           `json:"body_size"`
	UserID         int64         `json:"user_id,string"`
	Username       string        `json:"username"`
	// db log
	DBRunningFile  string        `json:"db_running_file"`
	DBRunningTime  time.Duration `json:"db_running_time"`
	DBSQL          string        `json:"db_sql"`
	DBParams       string        `json:"db_params"`
	DBEffectedRows string        `json:"db_effected_rows"`
	DBLogOrigin    string        `json:"db_log_origin"`
}

LogFormat log format struct

func (*LogFormat) GetString added in v0.0.40

func (l *LogFormat) GetString() string

GetString get logformat to string

type Logger

type Logger interface {
	Print(v ...interface{})
}

Logger to record log

func NewDefaultLogger added in v1.1.12

func NewDefaultLogger(userRequestsCtx UserRequestsCtx, setting ISetting) Logger

NewDefaultLogger new default logger

type Logmodel

type Logmodel struct {
	ID           int64      `json:"key,string"  gorm:"primary_key;AUTO_INCREMENT:false"`
	CreatedTime  *time.Time `json:"created_time" `
	CreateUser   *User      `json:"create_user"`
	CreateUserID int64      `json:"create_user_id,string" `
}

Logmodel common type

type Migration added in v0.0.8

type Migration struct {
	Simpmodel
	Seq    int    `json:"seq"  `
	Name   string `json:"name" gorm:"type:varchar(100);"`
	Status bool   `json:"status" gorm:"default:FALSE"`
	Error  string `json:"error" `
}

Migration model Migration

type MixinCallback added in v0.0.40

type MixinCallback func(r *ViewSetRunTime)

MixinCallback type

type Model

type Model struct {
	ID           int64      `json:"key,string"  gorm:"primary_key;AUTO_INCREMENT:false" mapstructure:"key"`
	CreatedTime  *time.Time `json:"created_time" `
	CreateUser   *User      `json:"create_user" `
	CreateUserID int64      `json:"create_user_id,string" `
	UpdatedTime  *time.Time `json:"updated_time"`
	UpdateUser   *User      `json:"update_user"`
	UpdateUserID int64      `json:"update_user_id,string" `
	DeletedTime  *time.Time `json:"deleted_time"`
	DeleteUser   *User      `json:"delete_user"`
	DeleteUserID int64      `json:"delete_user_id,string" `
	DVersion     string     `json:"d_version"`
}

Model common type

type NilLogger added in v1.1.11

type NilLogger struct{}

NilLogger nil logger

func (*NilLogger) Print added in v1.1.11

func (l *NilLogger) Print(v ...interface{})

Print nil logger do noothing

type PatchMixin

type PatchMixin struct {
	ViewSetRunTime *ViewSetRunTime
}

PatchMixin for Get request

func (*PatchMixin) Handler

func (r *PatchMixin) Handler()

Handler for handle patch request

type Permission

type Permission struct {
	Model
	Code string `json:"code" gorm:"type:varchar(100);index;unique;not null;"`
	Name string `json:"name" gorm:"type:varchar(100);not null;default:''"`
}

Permission model Role

func (*Permission) CreateOrInitPermission

func (p *Permission) CreateOrInitPermission(t *Trinity)

CreateOrInitPermission create or init permission

type Pool added in v1.1.8

type Pool struct {
	// contains filtered or unexported fields
}

Pool is the grpc client pool

func NewGRPCConnPoool added in v1.1.8

func NewGRPCConnPoool(factory Factory, init, capacity int, idleTimeout time.Duration,
	maxLifeDuration ...time.Duration) (*Pool, error)

NewGRPCConnPoool creates a new clients pool with the given initial and maximum capacity, and the timeout for the idle clients. Returns an error if the initial clients could not be created

func NewWithContext added in v1.1.8

func NewWithContext(ctx context.Context, factory FactoryWithContext, init, capacity int, idleTimeout time.Duration,
	maxLifeDuration ...time.Duration) (*Pool, error)

NewWithContext creates a new clients pool with the given initial and maximum capacity, and the timeout for the idle clients. The context parameter would be passed to the factory method during initialization. Returns an error if the initial clients could not be created.

func (*Pool) Available added in v1.1.8

func (p *Pool) Available() int

Available returns the number of currently unused clients

func (*Pool) Capacity added in v1.1.8

func (p *Pool) Capacity() int

Capacity returns the capacity

func (*Pool) Close added in v1.1.8

func (p *Pool) Close()

Close empties the pool calling Close on all its clients. You can call Close while there are outstanding clients. The pool channel is then closed, and Get will not be allowed anymore

func (*Pool) Get added in v1.1.8

func (p *Pool) Get(ctx context.Context) (*ClientConn, error)

Get will return the next available client. If capacity has not been reached, it will create a new one using the factory. Otherwise, it will wait till the next client becomes available or a timeout. A timeout of 0 is an indefinite wait

func (*Pool) IsClosed added in v1.1.8

func (p *Pool) IsClosed() bool

IsClosed returns true if the client pool is closed.

type PostMixin

type PostMixin struct {
	ViewSetRunTime *ViewSetRunTime
}

PostMixin for Get request

func (*PostMixin) Handler

func (r *PostMixin) Handler()

Handler for handle post request

type PutMixin

type PutMixin struct {
	ViewSetRunTime *ViewSetRunTime
}

PutMixin for Get request

func (*PutMixin) Handler

func (r *PutMixin) Handler()

Handler for handle put request

type ReqUserName added in v1.1.11

type ReqUserName string

ReqUserName request user name

type ResponseData

type ResponseData struct {
	Status  int         // the http response status  to return
	Result  interface{} // the response data  if req success
	TraceID string
}

ResponseData http response

type RetrieveMixin

type RetrieveMixin struct {
	ViewSetRunTime *ViewSetRunTime
}

RetrieveMixin for Get request

func (*RetrieveMixin) Handler

func (r *RetrieveMixin) Handler()

Handler for handle retrieve request

type Role added in v0.0.14

type Role struct {
	Model
	Name        string       `json:"name" gorm:"type:varchar(50);index;unique;not null;"`
	Description string       `json:"description" gorm:"type:varchar(100);not null;default:''"`
	Permissions []Permission `json:"permissions" gorm:"many2many:role_permissions;"`
}

Role model Role

type ServiceHandler added in v0.0.40

type ServiceHandler interface {
	Handler()
}

ServiceHandler for handle mixin

type ServiceMesh added in v1.1.7

type ServiceMesh interface {
	GetClient() interface{}
	RegService(projectName string, projectVersion string, serviceIP string, servicePort int, Tags []string, deregisterSecondAfterCritical int, interval int, tlsEnabled bool) error
	DeRegService(projectName string, projectVersion string, serviceIP string, servicePort int) error
}

ServiceMesh interface

func NewConsulRegister added in v1.1.7

func NewConsulRegister(consulAddress string, consulPort int) (ServiceMesh, error)

NewConsulRegister New consul register

func NewEtcdRegister added in v1.1.7

func NewEtcdRegister(address string, port int) (ServiceMesh, error)

NewEtcdRegister New consul register

type ServiceMeshConsulImpl added in v1.1.7

type ServiceMeshConsulImpl struct {
	// config
	ConsulAddress string // consul address
	ConsulPort    int
	// contains filtered or unexported fields
}

ServiceMeshConsulImpl consul register

func (*ServiceMeshConsulImpl) DeRegService added in v1.1.7

func (c *ServiceMeshConsulImpl) DeRegService(projectName string, projectVersion string, serviceIP string, servicePort int) error

DeRegService deregister service

func (*ServiceMeshConsulImpl) GetClient added in v1.1.7

func (c *ServiceMeshConsulImpl) GetClient() interface{}

GetClient get consul client

func (*ServiceMeshConsulImpl) RegService added in v1.1.7

func (c *ServiceMeshConsulImpl) RegService(projectName string, projectVersion string, serviceIP string, servicePort int, Tags []string, deregisterSecondAfterCritical int, interval int, tlsEnabled bool) error

RegService consul register service

type ServiceMeshEtcdImpl added in v1.1.7

type ServiceMeshEtcdImpl struct {
	// config
	Address string // consul address
	Port    int
	// contains filtered or unexported fields
}

ServiceMeshEtcdImpl consul register

func (*ServiceMeshEtcdImpl) DeRegService added in v1.1.7

func (s *ServiceMeshEtcdImpl) DeRegService(projectName string, projectVersion string, serviceIP string, servicePort int) error

DeRegService deregister service

func (*ServiceMeshEtcdImpl) GetClient added in v1.1.7

func (s *ServiceMeshEtcdImpl) GetClient() interface{}

GetClient get etcd client

func (*ServiceMeshEtcdImpl) RegService added in v1.1.7

func (s *ServiceMeshEtcdImpl) RegService(projectName string, projectVersion string, serviceIP string, servicePort int, Tags []string, deregisterSecondAfterCritical int, interval int, tlsEnabled bool) error

RegService register etcd service

type Setting

type Setting struct {
	Project string   `yaml:"project"`
	Version string   `yaml:"version"`
	Tags    []string `yaml:"tags"`
	Runtime struct {
		Debug bool `yaml:"debug"`
	}
	Security struct {
		Authentication struct {
			SecretKey           string `yaml:"secretkey"`
			JwtVerifyIssuer     bool   `yaml:"jwtverifyissuer"`
			JwtIssuer           string `yaml:"jwtissuer"`
			JwtVerifyExpireHour bool   `yaml:"jwtverifyexpirehour"`
			JwtExpireHour       int    `yaml:"jwtexpirehour"`
			JwtHeaderPrefix     string `yaml:"jwtheaderprefix"`
		}
		Cors struct {
			Enable           bool     `yaml:"enable"`
			AllowOrigins     []string `yaml:"alloworigins"`
			AllowMethods     []string `yaml:"allowmethods"`
			AllowHeaders     []string `yaml:"allowheaders"`
			ExposeHeaders    []string `yaml:"exposeheaders"`
			AllowCredentials bool     `yaml:"allowcredentials"`
			MaxAgeHour       int      `yaml:"maxagehour"`
		}
		TLS struct {
			Enabled       bool   `yaml:"enabled"`
			CAPemFile     string `yaml:"ca_pem_file"`
			ServerPemFile string `yaml:"server_pem_file"`
			ServerKeyFile string `yaml:"server_key_file"`
			ClientPemFile string `yaml:"client_pem_file"`
			ClientKeyFile string `yaml:"client_key_file"`
		}
	}
	Webapp struct {
		// Type support GRPC HTTP
		Type    string `yaml:"type"`
		Address string `yaml:"address"`
		Port    int    `yaml:"port"`
		// ReadTimeout is the maximum duration for reading the entire
		// request, including the body.
		//
		// Because ReadTimeout does not let Handlers make per-request
		// decisions on each request body's acceptable deadline or
		// upload rate, most users will prefer to use
		// ReadHeaderTimeout. It is valid to use them both.
		ReadTimeoutSecond int `yaml:"readtimeoutsecond"`

		// ReadHeaderTimeout is the amount of time allowed to read
		// request headers. The connection's read deadline is reset
		// after reading the headers and the Handler can decide what
		// is considered too slow for the body. If ReadHeaderTimeout
		// is zero, the value of ReadTimeout is used. If both are
		// zero, there is no timeout.
		ReadHeaderTimeoutSecond int `yaml:"readheadertimeoutsecond"`

		// WriteTimeout is the maximum duration before timing out
		// writes of the response. It is reset whenever a new
		// request's header is read. Like ReadTimeout, it does not
		// let Handlers make decisions on a per-request basis.
		WriteTimeoutSecond int `yaml:"writertimeoutsecond"`

		// IdleTimeout is the maximum amount of time to wait for the
		// next request when keep-alives are enabled. If IdleTimeout
		// is zero, the value of ReadTimeout is used. If both are
		// zero, there is no timeout.
		IdleTimeoutSecond int `yaml:"idletimeoutsecond"`

		// MaxHeaderBytes controls the maximum number of bytes the
		// server will read parsing the request header's keys and
		// values, including the request line. It does not limit the
		// size of the request body.
		// If zero, DefaultMaxHeaderBytes is used.
		MaxHeaderBytes int    `yaml:"maxheaderbytes"`
		TemplatePath   string `yaml:"templatepath"`
		MediaURL       string `yaml:"mediaurl"`
		MediaPath      string `yaml:"mediapath"`
		StaticURL      string `yaml:"staticurl"`
		StaticPath     string `yaml:"staticpath"`
		MigrationPath  string `yaml:"migrationpath"`
		PageSize       int    `yaml:"pagesize"`
		MaxBodySize    int    `yaml:"maxbodysize"`
		AtomicRequest  bool   `yaml:"atomicrequest"`
		// if api root is not root , replease with base url
		// e.g : /assetgo
		BaseURL string `yaml:"baseurl"`
	}
	Log struct {
		Enable      bool   `yaml:"enable"`
		LogRootPath string `yaml:"logrootpath"` //   /var/log/mold
		LogName     string `yaml:"logname"`     //  app.log
	}
	Cache struct {
		Redis struct {
			Host        string
			Port        int
			Password    string
			Maxidle     int
			Maxactive   int
			Idletimeout int
		}
		Gcache struct {
			CacheAlgorithm string `yaml:"cache_algorithm"`
			CacheSize      int    `yaml:"cachesize"`
			Timeout        int    `yaml:"timeout"` // hour
		}
	}
	Database struct {
		Type          string
		Name          string
		User          string
		Password      string
		Host          string
		Port          string
		Option        string
		TablePrefix   string
		DbMaxIdleConn int
		DbMaxOpenConn int
	}
	ServiceMesh struct {
		Type                    string // etcd oor consul
		Address                 string
		Port                    int
		DeregisterAfterCritical int  `yaml:"deregister_after_critical"` //second
		HealthCheckInterval     int  `yaml:"health_check_interval"`     //second
		AutoRegister            bool `yaml:"auto_register"`
	}
	// contains filtered or unexported fields
}

Setting : for trinity setting

func (*Setting) GetAllowCredentials added in v1.1.11

func (s *Setting) GetAllowCredentials() bool

GetAllowCredentials get allow credentials

func (*Setting) GetAllowHeaders added in v1.1.11

func (s *Setting) GetAllowHeaders() []string

GetAllowHeaders get allow headers

func (*Setting) GetAllowMethods added in v1.1.11

func (s *Setting) GetAllowMethods() []string

GetAllowMethods get allow method

func (*Setting) GetAllowOrigins added in v1.1.11

func (s *Setting) GetAllowOrigins() []string

GetAllowOrigins get allow origins

func (*Setting) GetAtomicRequest added in v1.1.9

func (s *Setting) GetAtomicRequest() bool

GetAtomicRequest get automic request is open

func (*Setting) GetCAPemFile added in v1.1.7

func (s *Setting) GetCAPemFile() string

GetCAPemFile get ca pem file

func (*Setting) GetCacheSize added in v1.1.11

func (s *Setting) GetCacheSize() int

GetCacheSize get GetCacheSize

func (*Setting) GetCacheTimeout added in v1.1.11

func (s *Setting) GetCacheTimeout() int

GetCacheTimeout get GetCacheTimeout

func (*Setting) GetClientKeyFile added in v1.1.7

func (s *Setting) GetClientKeyFile() string

GetClientKeyFile get client key file

func (*Setting) GetClientPemFile added in v1.1.7

func (s *Setting) GetClientPemFile() string

GetClientPemFile get client pem file

func (*Setting) GetCorsEnable added in v1.1.11

func (s *Setting) GetCorsEnable() bool

GetCorsEnable get if enable cors

func (*Setting) GetDBHost added in v1.1.11

func (s *Setting) GetDBHost() string

GetDBHost get db host

func (*Setting) GetDBName added in v1.1.11

func (s *Setting) GetDBName() string

GetDBName get schema name

func (*Setting) GetDBOption added in v1.1.11

func (s *Setting) GetDBOption() string

GetDBOption get db option

func (*Setting) GetDBPassword added in v1.1.11

func (s *Setting) GetDBPassword() string

GetDBPassword get db password

func (*Setting) GetDBPort added in v1.1.11

func (s *Setting) GetDBPort() string

GetDBPort get db port

func (*Setting) GetDBType added in v1.1.11

func (s *Setting) GetDBType() string

GetDBType get db type

func (*Setting) GetDBUser added in v1.1.11

func (s *Setting) GetDBUser() string

GetDBUser get db user

func (*Setting) GetDbMaxIdleConn added in v1.1.11

func (s *Setting) GetDbMaxIdleConn() int

GetDbMaxIdleConn get db max idle connection

func (*Setting) GetDbMaxOpenConn added in v1.1.11

func (s *Setting) GetDbMaxOpenConn() int

GetDbMaxOpenConn get db max open connection

func (*Setting) GetDebug added in v1.1.7

func (s *Setting) GetDebug() bool

GetDebug get debug

func (*Setting) GetDeregisterAfterCritical added in v1.1.7

func (s *Setting) GetDeregisterAfterCritical() int

GetDeregisterAfterCritical deregister service after critical second

func (*Setting) GetExposeHeaders added in v1.1.11

func (s *Setting) GetExposeHeaders() []string

GetExposeHeaders get expoose headers

func (*Setting) GetHealthCheckInterval added in v1.1.7

func (s *Setting) GetHealthCheckInterval() int

GetHealthCheckInterval health check interval

func (*Setting) GetIdleTimeoutSecond added in v1.1.11

func (s *Setting) GetIdleTimeoutSecond() int

GetIdleTimeoutSecond get GetIdleTimeoutSecond

func (*Setting) GetJwtExpireHour added in v1.1.11

func (s *Setting) GetJwtExpireHour() int

GetJwtExpireHour get GetJwtExpireHour

func (*Setting) GetJwtHeaderPrefix added in v1.1.11

func (s *Setting) GetJwtHeaderPrefix() string

GetJwtHeaderPrefix get GetJwtHeaderPrefix

func (*Setting) GetJwtIssuer added in v1.1.11

func (s *Setting) GetJwtIssuer() string

GetJwtIssuer get GetJwtIssuer

func (*Setting) GetJwtVerifyExpireHour added in v1.1.11

func (s *Setting) GetJwtVerifyExpireHour() bool

GetJwtVerifyExpireHour get GetJwtVerifyExpireHour

func (*Setting) GetJwtVerifyIssuer added in v1.1.11

func (s *Setting) GetJwtVerifyIssuer() bool

GetJwtVerifyIssuer get GetJwtVerifyIssuer

func (*Setting) GetLogEnable added in v1.1.13

func (s *Setting) GetLogEnable() bool

GetLogEnable get log enable

func (*Setting) GetLogName added in v1.1.7

func (s *Setting) GetLogName() string

GetLogName get log name

func (*Setting) GetLogRootPath added in v1.1.7

func (s *Setting) GetLogRootPath() string

GetLogRootPath get log root path

func (*Setting) GetMaxAgeHour added in v1.1.11

func (s *Setting) GetMaxAgeHour() int

GetMaxAgeHour get max age hour

func (*Setting) GetMaxHeaderBytes added in v1.1.11

func (s *Setting) GetMaxHeaderBytes() int

GetMaxHeaderBytes get GetMaxHeaderBytes

func (*Setting) GetMigrationPath added in v1.1.11

func (s *Setting) GetMigrationPath() string

GetMigrationPath get GetMigrationPath

func (*Setting) GetPageSize added in v1.1.11

func (s *Setting) GetPageSize() int

GetPageSize get GetPageSize

func (*Setting) GetProjectName added in v1.1.7

func (s *Setting) GetProjectName() string

GetProjectName get project name

func (*Setting) GetProjectVersion added in v1.1.7

func (s *Setting) GetProjectVersion() string

GetProjectVersion get project name

func (*Setting) GetReadHeaderTimeoutSecond added in v1.1.11

func (s *Setting) GetReadHeaderTimeoutSecond() int

GetReadHeaderTimeoutSecond get GetReadHeaderTimeoutSecond

func (*Setting) GetReadTimeoutSecond added in v1.1.11

func (s *Setting) GetReadTimeoutSecond() int

GetReadTimeoutSecond get readtimeoout

func (*Setting) GetSecretKey added in v1.1.11

func (s *Setting) GetSecretKey() string

GetSecretKey get GetSecretKey

func (*Setting) GetServerKeyFile added in v1.1.7

func (s *Setting) GetServerKeyFile() string

GetServerKeyFile get server key file

func (*Setting) GetServerPemFile added in v1.1.7

func (s *Setting) GetServerPemFile() string

GetServerPemFile get server pem file

func (*Setting) GetServiceMeshAddress added in v1.1.7

func (s *Setting) GetServiceMeshAddress() string

GetServiceMeshAddress get service mesh address

func (*Setting) GetServiceMeshAutoRegister added in v1.1.11

func (s *Setting) GetServiceMeshAutoRegister() bool

GetServiceMeshAutoRegister get auto register

func (*Setting) GetServiceMeshPort added in v1.1.7

func (s *Setting) GetServiceMeshPort() int

GetServiceMeshPort get service mesh port

func (*Setting) GetServiceMeshType added in v1.1.7

func (s *Setting) GetServiceMeshType() string

GetServiceMeshType get s m type

func (*Setting) GetSetting added in v1.1.7

func (s *Setting) GetSetting() *Setting

GetSetting get setting

func (*Setting) GetTLSEnabled added in v1.1.7

func (s *Setting) GetTLSEnabled() bool

GetTLSEnabled get tls enabled

func (*Setting) GetTablePrefix added in v1.1.11

func (s *Setting) GetTablePrefix() string

GetTablePrefix get table prefix

func (*Setting) GetTags added in v1.1.7

func (s *Setting) GetTags() []string

GetTags get project tags

func (*Setting) GetWebAppAddress added in v1.1.7

func (s *Setting) GetWebAppAddress() string

GetWebAppAddress get web service ip address

func (*Setting) GetWebAppBaseURL added in v1.1.11

func (s *Setting) GetWebAppBaseURL() string

GetWebAppBaseURL get GetWebAppBaseURL

func (*Setting) GetWebAppMediaPath added in v1.1.11

func (s *Setting) GetWebAppMediaPath() string

GetWebAppMediaPath get web app media path

func (*Setting) GetWebAppMediaURL added in v1.1.11

func (s *Setting) GetWebAppMediaURL() string

GetWebAppMediaURL get web app media url

func (*Setting) GetWebAppPort added in v1.1.7

func (s *Setting) GetWebAppPort() int

GetWebAppPort get web service port

func (*Setting) GetWebAppStaticPath added in v1.1.11

func (s *Setting) GetWebAppStaticPath() string

GetWebAppStaticPath get web app static path

func (*Setting) GetWebAppStaticURL added in v1.1.11

func (s *Setting) GetWebAppStaticURL() string

GetWebAppStaticURL get web app static url

func (*Setting) GetWebAppType added in v1.1.7

func (s *Setting) GetWebAppType() string

GetWebAppType get web app type

func (*Setting) GetWriteTimeoutSecond added in v1.1.11

func (s *Setting) GetWriteTimeoutSecond() int

GetWriteTimeoutSecond get GetWriteTimeoutSecond

type Simpmodel

type Simpmodel struct {
	ID          int64      `json:"key,string"  gorm:"primary_key;AUTO_INCREMENT:false"`
	CreatedTime *time.Time `json:"created_time" `
}

Simpmodel common type

type TraceID added in v1.1.11

type TraceID string

TraceID current request trace id

type Trinity

type Trinity struct {
	// contains filtered or unexported fields
}

Trinity struct for app subconfig

var (
	// GlobalTrinity global instance
	GlobalTrinity *Trinity
)

func New

func New(customizeSetting ...CustomizeSetting) *Trinity

New app initial global trinity object

func (*Trinity) CleanCache added in v0.0.41

func (t *Trinity) CleanCache()

CleanCache clean the current cache

func (*Trinity) Close

func (t *Trinity) Close()

Close http

func (*Trinity) GetCache added in v0.0.28

func (t *Trinity) GetCache() gcache.Cache

GetCache get vcfg

func (*Trinity) GetDB added in v0.0.10

func (t *Trinity) GetDB() *gorm.DB

GetDB get db instance

func (*Trinity) GetGRPCServer added in v1.1.7

func (t *Trinity) GetGRPCServer() *grpc.Server

GetGRPCServer get grpc server instance

func (*Trinity) GetLogger added in v1.1.7

func (t *Trinity) GetLogger() Logger

GetLogger get vcfg

func (*Trinity) GetRouter added in v0.0.10

func (t *Trinity) GetRouter() *gin.Engine

GetRouter get router

func (*Trinity) GetSetting added in v0.0.10

func (t *Trinity) GetSetting() ISetting

GetSetting get setting

func (*Trinity) GetVCfg added in v0.0.10

func (t *Trinity) GetVCfg() *ViewSetCfg

GetVCfg get vcfg

func (*Trinity) InitDatabase

func (t *Trinity) InitDatabase()

InitDatabase create db connection *

  • initial db connection

func (*Trinity) Migrate added in v0.0.40

func (t *Trinity) Migrate(modelToMigrate ...interface{})

Migrate to migrate model

func (*Trinity) NewAPIGroup

func (t *Trinity) NewAPIGroup(path string) *gin.RouterGroup

NewAPIGroup register new apigroup

func (*Trinity) Serve

func (t *Trinity) Serve()

Serve http

func (*Trinity) ServeGRPC added in v1.1.7

func (t *Trinity) ServeGRPC()

ServeGRPC serve GRPC

func (*Trinity) ServeHTTP added in v1.1.7

func (t *Trinity) ServeHTTP()

ServeHTTP serve HTTP

func (*Trinity) SetCache added in v0.0.28

func (t *Trinity) SetCache(cache gcache.Cache) *Trinity

SetCache get vcfg

type UnknownMixin

type UnknownMixin struct {
	ViewSetRunTime *ViewSetRunTime
}

UnknownMixin for Get request

func (*UnknownMixin) Handler

func (r *UnknownMixin) Handler()

Handler for handle Unknown request

type User

type User struct {
	Model
	Username           string       `json:"username" gorm:"type:varchar(50);index;not null;"`             // login username /profile
	NameLocal          string       `json:"name_local"  gorm:"type:varchar(50);" `                        // local name
	NameEN             string       `json:"name_en"  gorm:"type:varchar(50);" `                           // EN name
	Email              string       `json:"email"  gorm:"type:varchar(50);" `                             // login email
	Phone              string       `json:"phone" gorm:"type:varchar(50);" `                              // login phone
	Groups             []Group      `json:"groups" gorm:"many2many:user_groups;"`                         // foreign key -->group
	Permissions        []Permission `json:"permissions" gorm:"many2many:user_permissions;"`               // foreign key --->permission
	PreferenceLanguage string       `json:"preference_language" gorm:"type:varchar(50);default:'en-US'" ` // user preference language

}

User model User

type UserRequestsCtx added in v1.1.12

type UserRequestsCtx interface {
	GetGRPCMethod() GRPCMethod
	GetTraceID() TraceID
	GetReqUserName() ReqUserName
}

UserRequestsCtx handle user ctx from context

func NewUserRequestsCtx added in v1.1.12

func NewUserRequestsCtx(ctx context.Context) UserRequestsCtx

NewUserRequestsCtx new user ctx

type UserRequestsCtxImpl added in v1.1.12

type UserRequestsCtxImpl struct {
	// contains filtered or unexported fields
}

UserRequestsCtxImpl UserRequestsCtxImpl handler request ctx , extrace data from ctx

func (*UserRequestsCtxImpl) GetGRPCMethod added in v1.1.12

func (u *UserRequestsCtxImpl) GetGRPCMethod() GRPCMethod

GetGRPCMethod get grpc method

func (*UserRequestsCtxImpl) GetReqUserName added in v1.1.12

func (u *UserRequestsCtxImpl) GetReqUserName() ReqUserName

GetReqUserName get request user

func (*UserRequestsCtxImpl) GetTraceID added in v1.1.12

func (u *UserRequestsCtxImpl) GetTraceID() TraceID

GetTraceID get trace id

type ViewSetCfg

type ViewSetCfg struct {

	// global config
	Db *gorm.DB
	// if do the atomic request
	AtomicRequestMap map[string]bool
	// HasAuthCtl
	// if do the auth check ,default false
	HasAuthCtl bool
	// AuthenticationBackendMap
	// if HasAuthCtl == false ; pass... customize the authentication check , default jwt  ;
	// please set UserID in context
	// e.g : c.Set("UserID", tokenClaims.UID)
	AuthenticationBackendMap map[string]func(c *gin.Context) error
	// GetCurrentUserAuth
	// must be type : func(c *gin.Context, db *gorm.DB) error
	// if HasAuthCtl == false ; pass...
	// get user auth func with UserID if you set in AuthenticationBackend
	// please set UserPermission and UserKey in context
	// e.g : c.Set("UserKey",UserKey) with c.GetString("UserID")
	// e.g : c.Set("UserPermission", UserPermission) with c.GetString("UserID")
	GetCurrentUserAuth func(c *gin.Context, db *gorm.DB) error
	// AccessBackendReqMap
	// if HasAuthCtl == false ; pass... customize the access require permission
	AccessBackendRequireMap map[string][]string
	// AccessBackendCheckMap
	// if HasAuthCtl == false ; pass... customize the access check , check user permission
	// e.g : userPermission :=  c.GetString("UserPermission")
	// e.g : requiredPermission := []string{"123"} get with AccessBackendReqMap by default
	// e.g : trinity.CheckAccessAuthorization(requiredPermission , userPermission) , true?allow:deny
	AccessBackendCheckMap map[string]func(v *ViewSetRunTime) error
	// PreloadListMap gorm preload list
	PreloadListMap map[string]map[string]func(db *gorm.DB) *gorm.DB
	// FilterBackendMap : all the query will with this filter backend
	FilterBackendMap map[string]func(c *gin.Context, db *gorm.DB) *gorm.DB
	// FilterByList : only in FilterByList will do the filter
	FilterByList []string
	// FilterCustomizeFunc : can do the customize filter ,mapping with FilterByList
	FilterCustomizeFunc map[string]func(db *gorm.DB, queryValue string) *gorm.DB
	// SearchingByList : with keyword "SearchBy" on url query ,
	// will do the where (xxx =? or xxx=?)
	SearchingByList []string
	// OrderingByList : with keyword "OrderBy" on url query ,
	// only define in OrderingByList will do the order by
	// e.g: OrderBy=xxx-   ==> order by xxx desc
	// e.g: OrderBy=xxx   ==> order by xxx asc
	OrderingByList map[string]bool
	// PageSize default 10
	// keyword : PageNum , PageSize to do the limit and offset
	PageSize      int
	EnableOrderBy bool
	// EnableChangeLog enable change log
	EnableChangeLog bool
	// EnableDataVersion check
	EnableDataVersion bool
	// EnableHistory enable history version
	EnableVersionControl bool
	// Retrieve
	BeforeRetrieve MixinCallback
	Retrieve       MixinCallback
	AfterRetrieve  MixinCallback

	// Get
	BeforeGet MixinCallback
	Get       MixinCallback
	AfterGet  MixinCallback

	// Post
	PostValidation interface{}
	BeforePost     MixinCallback
	Post           MixinCallback
	AfterPost      MixinCallback

	// Put
	PutValidation interface{}
	BeforePut     MixinCallback
	Put           MixinCallback
	AfterPut      MixinCallback

	// Patch
	PatchValidation interface{}
	BeforePatch     MixinCallback
	Patch           MixinCallback
	AfterPatch      MixinCallback

	// Delete
	BeforeDelete MixinCallback
	Delete       MixinCallback
	AfterDelete  MixinCallback
	// contains filtered or unexported fields
}

ViewSetCfg for viewset config

func NewViewSet

func NewViewSet() *ViewSetCfg

NewViewSet new api viewset

func (*ViewSetCfg) NewRunTime

func (v *ViewSetCfg) NewRunTime(c *gin.Context, ResourceModel interface{}, ModelSerializer interface{}, ModelSerializerlist interface{}) *ViewSetRunTime

NewRunTime : new the run time with the default config ResourceModel : the main resource model . decide the access authorization and the table name for the resource ModelSerializer : the serializer model , used for retrieve , post and patch service, ModelSerializerlist : the serializer model , used for get

type ViewSetRunTime

type ViewSetRunTime struct {
	TraceID string
	Method  string
	// is atomic request
	IsAtomicRequest bool
	// gin.context
	Gcontext *gin.Context
	// db instance
	Db *gorm.DB
	// ResourceModel
	// target resource model
	ResourceModel     interface{} // ResourceModel for the resource
	ResourceTableName string
	// resource serializer , used to limit the retrieve object
	ModelSerializer interface{}
	// ModelSerializerlist
	// resource serializer , used to limit the get object list
	ModelSerializerlist interface{}
	// HasAuthCtl
	// if do the auth check ,default false
	HasAuthCtl            bool
	AuthenticationBackend func(c *gin.Context) error
	GetCurrentUserAuth    func(c *gin.Context, db *gorm.DB) error
	AccessBackendRequire  []string
	AccessBackendCheck    func(v *ViewSetRunTime) error
	DBFilterBackend       func(db *gorm.DB) *gorm.DB // current dbfilterbackend
	PreloadList           map[string]func(db *gorm.DB) *gorm.DB
	FilterBackend         func(c *gin.Context, db *gorm.DB) *gorm.DB
	FilterByList          []string
	FilterCustomizeFunc   map[string]func(db *gorm.DB, queryValue string) *gorm.DB
	SearchingByList       []string
	OrderingByList        map[string]bool
	PageSize              int
	EnableOrderBy         bool
	EnableChangeLog       bool
	EnableDataVersion     bool
	EnableVersionControl  bool

	// Retrieve
	BeforeRetrieve MixinCallback
	Retrieve       MixinCallback
	AfterRetrieve  MixinCallback

	// Get
	BeforeGet MixinCallback
	Get       MixinCallback
	AfterGet  MixinCallback

	// Post
	PostValidation interface{}
	BeforePost     MixinCallback
	Post           MixinCallback
	AfterPost      MixinCallback

	// Put
	PutValidation interface{}
	BeforePut     MixinCallback
	Put           MixinCallback
	AfterPut      MixinCallback

	// Patch
	PatchValidation interface{}
	BeforePatch     MixinCallback
	Patch           MixinCallback
	AfterPatch      MixinCallback

	// Delete
	BeforeDelete MixinCallback
	Delete       MixinCallback
	AfterDelete  MixinCallback

	Cfg      *ViewSetCfg
	DBLogger Logger

	//response handle
	Status    int
	ResBody   interface{}
	FuncName  uintptr
	File      string
	Line      int
	RealError error
	UserError error
	// contains filtered or unexported fields
}

ViewSetRunTime : put runtime data

func (*ViewSetRunTime) HandleResponse

func (v *ViewSetRunTime) HandleResponse(status int, payload interface{}, rerr error, uerr error)

HandleResponse handle response

func (*ViewSetRunTime) Response

func (v *ViewSetRunTime) Response()

Response handle trinity return value

func (*ViewSetRunTime) ViewSetServe

func (v *ViewSetRunTime) ViewSetServe()

ViewSetServe for viewset handle serve flow

if HasAuthCtl == false {
	1.AuthenticationBackend : do the authentication check , normally get the user identity
	2.GetCurrentUserAuth : get the user permission information
	3.AccessBackend : do the access check
}

4.request data validation 5.DbWithBackend : do the DB backend check 6.do the request

type Viewmodel

type Viewmodel struct {
	ID           int64      `json:"key,string"  gorm:"primary_key;AUTO_INCREMENT:false"`
	CreatedTime  *time.Time `json:"created_time" `
	CreateUser   *User      `json:"create_user"`
	CreateUserID int64      `json:"create_user_id,string"`
	UpdatedTime  *time.Time `json:"updated_time" `
	UpdateUser   *User      `json:"update_user"`
	UpdateUserID int64      `json:"update_user_id,string"`
	DeletedTime  *time.Time `json:"deleted_time" `
	DeleteUser   *User      `json:"delete_user"`
	DeleteUserID int64      `json:"delete_user_id,string"`
}

Viewmodel for view type

Jump to

Keyboard shortcuts

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