Documentation ¶
Index ¶
- Constants
- Variables
- func CheckAccessAuthorization(requiredPermission, userPermission []string) error
- func CheckFileIsExist(filename string) bool
- func ConsulResolverInit(address string, serviceName string) error
- func DataVersionFilter(param interface{}, isCheck bool) func(db *gorm.DB) *gorm.DB
- func DbLoggerFormatter(r *ViewSetRunTime, v ...interface{}) string
- func DefaultAccessBackend(v *ViewSetRunTime) error
- func DefaultDeleteCallback(r *ViewSetRunTime)
- func DefaultFilterBackend(c *gin.Context, db *gorm.DB) *gorm.DB
- func DefaultGetCallback(r *ViewSetRunTime)
- func DefaultPatchCallback(r *ViewSetRunTime)
- func DefaultPostCallback(r *ViewSetRunTime)
- func DefaultPutCallback(r *ViewSetRunTime)
- func DefaultRetrieveCallback(r *ViewSetRunTime)
- func DeleteExtraSpace(s string) string
- func DeleteHandler(r *DeleteMixin)
- func FilterByCustomizeCondition(ok bool, k string, v ...interface{}) func(db *gorm.DB) *gorm.DB
- func FilterByFilter(c *gin.Context, FilterByList []string, ...) func(db *gorm.DB) *gorm.DB
- func FilterByParam(param int64) func(db *gorm.DB) *gorm.DB
- func FilterBySearch(c *gin.Context, SearchingByList []string) func(db *gorm.DB) *gorm.DB
- func GenerateSnowFlakeID(nodenumber int64) int64
- func GenerateToken(userkey string) (string, error, error)
- func GetCurrentTime() time.Time
- func GetCurrentTimeString(timeType string) string
- func GetCurrentTimeUnix() int64
- func GetFreePort() (int, error)
- func GetHandler(r *GetMixin)
- func GetRequestType(c *gin.Context) string
- func GetServiceID(projectName string, projectVersion string, ServiceIP string, ServicePort int) string
- func GetServiceName(projectName string) string
- func GetTypeName(myvar interface{}, isToLowerCase bool) string
- func Getparentdirectory(path string, level int) string
- func HandleBackend(c *gin.Context, backend func(c *gin.Context, db *gorm.DB) *gorm.DB) func(db *gorm.DB) *gorm.DB
- func HandleFilterBackend(v *ViewSetCfg, method string, c *gin.Context) func(db *gorm.DB) *gorm.DB
- func HandlestructBySelect(c *gin.Context, resource interface{}) (int, interface{}, error)
- func InSlice(value string, stringSlice []string) bool
- func IsFuncInited(function MixinCallback) bool
- func JWTMiddleWare() gin.HandlerFunc
- func JwtAuthBackend(c *gin.Context) (error, error)
- func JwtUnverifiedAuthBackend(c *gin.Context) error
- func LoadConfigError(err error)
- func LoadCustomizeSetting(customizeSettingSlice ...CustomizeSetting)
- func LogMiddleware() gin.HandlerFunc
- func LogPrint(v ...interface{})
- func LoggingInterceptor(log Logger, setting ISetting) ...
- func NewAPIInGroup(rg *gin.RouterGroup, resource string, viewset gin.HandlerFunc, ...)
- func NewEtcdClientConn(address string, port int, serviceName string) (*grpc.ClientConn, error)
- func PatchHandler(r *PatchMixin)
- func PostHandler(r *PostMixin)
- func PutHandler(r *PutMixin)
- func QueryByOrdering(c *gin.Context, EnableOrderBy bool, OrderingByList map[string]bool) func(db *gorm.DB) *gorm.DB
- func QueryByPagination(c *gin.Context, PageSize int) func(db *gorm.DB) *gorm.DB
- func QueryByPreload(PreloadList map[string]func(db *gorm.DB) *gorm.DB) func(db *gorm.DB) *gorm.DB
- func QueryBySelect(c *gin.Context) func(db *gorm.DB) *gorm.DB
- func RecordErrorLevelTwo() (uintptr, string, int)
- func RecoveryInterceptor(log Logger) ...
- func RetriveHandler(r *RetrieveMixin)
- func RunMigration()
- func SetConfigFilePath(path string)
- func SetDefaultWriter(writer io.Writer)
- func SetRunMode(runmode string)
- func SliceInSlice(sliceToCheck []string, slice []string) bool
- func UserAuthInterceptor(log Logger) ...
- func WrongRunMode(runmode string)
- type AppChangelog
- type AppError
- type AutoModel
- type Claims
- type ClientConn
- type Context
- type ContextImpl
- type CustomizeSetting
- type DeleteMixin
- type Factory
- type FactoryWithContext
- type FedidClaims
- type FilterQuery
- type GRPCMethod
- type GetMixin
- type GlobalSetting
- type Group
- type ISetting
- type LogFormat
- type Logger
- type Logmodel
- type Migration
- type MixinCallback
- type Model
- type NilLogger
- type PatchMixin
- type Permission
- type Pool
- type PostMixin
- type PutMixin
- type ReqUserName
- type ResponseData
- type RetrieveMixin
- type Role
- type ServiceHandler
- type ServiceMesh
- type ServiceMeshConsulImpl
- func (c *ServiceMeshConsulImpl) DeRegService(projectName string, projectVersion string, serviceIP string, servicePort int) error
- func (c *ServiceMeshConsulImpl) GetClient() interface{}
- func (c *ServiceMeshConsulImpl) RegService(projectName string, projectVersion string, serviceIP string, servicePort int, ...) error
- type ServiceMeshEtcdImpl
- func (s *ServiceMeshEtcdImpl) DeRegService(projectName string, projectVersion string, serviceIP string, servicePort int) error
- func (s *ServiceMeshEtcdImpl) GetClient() interface{}
- func (s *ServiceMeshEtcdImpl) RegService(projectName string, projectVersion string, serviceIP string, servicePort int, ...) error
- type Setting
- func (s *Setting) GetAllowCredentials() bool
- func (s *Setting) GetAllowHeaders() []string
- func (s *Setting) GetAllowMethods() []string
- func (s *Setting) GetAllowOrigins() []string
- func (s *Setting) GetAtomicRequest() bool
- func (s *Setting) GetCAPemFile() string
- func (s *Setting) GetCacheSize() int
- func (s *Setting) GetCacheTimeout() int
- func (s *Setting) GetClientKeyFile() string
- func (s *Setting) GetClientPemFile() string
- func (s *Setting) GetCorsEnable() bool
- func (s *Setting) GetDBHost() string
- func (s *Setting) GetDBName() string
- func (s *Setting) GetDBOption() string
- func (s *Setting) GetDBPassword() string
- func (s *Setting) GetDBPort() string
- func (s *Setting) GetDBType() string
- func (s *Setting) GetDBUser() string
- func (s *Setting) GetDbMaxIdleConn() int
- func (s *Setting) GetDbMaxOpenConn() int
- func (s *Setting) GetDebug() bool
- func (s *Setting) GetDeregisterAfterCritical() int
- func (s *Setting) GetExposeHeaders() []string
- func (s *Setting) GetHealthCheckInterval() int
- func (s *Setting) GetIdleTimeoutSecond() int
- func (s *Setting) GetJwtExpireHour() int
- func (s *Setting) GetJwtHeaderPrefix() string
- func (s *Setting) GetJwtIssuer() string
- func (s *Setting) GetJwtVerifyExpireHour() bool
- func (s *Setting) GetJwtVerifyIssuer() bool
- func (s *Setting) GetLogEnable() bool
- func (s *Setting) GetLogName() string
- func (s *Setting) GetLogRootPath() string
- func (s *Setting) GetMaxAgeHour() int
- func (s *Setting) GetMaxHeaderBytes() int
- func (s *Setting) GetMigrationPath() string
- func (s *Setting) GetPageSize() int
- func (s *Setting) GetProjectName() string
- func (s *Setting) GetProjectVersion() string
- func (s *Setting) GetReadHeaderTimeoutSecond() int
- func (s *Setting) GetReadTimeoutSecond() int
- func (s *Setting) GetSecretKey() string
- func (s *Setting) GetServerKeyFile() string
- func (s *Setting) GetServerPemFile() string
- func (s *Setting) GetServiceMeshAddress() string
- func (s *Setting) GetServiceMeshAutoRegister() bool
- func (s *Setting) GetServiceMeshPort() int
- func (s *Setting) GetServiceMeshType() string
- func (s *Setting) GetSetting() *Setting
- func (s *Setting) GetTLSEnabled() bool
- func (s *Setting) GetTablePrefix() string
- func (s *Setting) GetTags() []string
- func (s *Setting) GetWebAppAddress() string
- func (s *Setting) GetWebAppBaseURL() string
- func (s *Setting) GetWebAppMediaPath() string
- func (s *Setting) GetWebAppMediaURL() string
- func (s *Setting) GetWebAppPort() int
- func (s *Setting) GetWebAppStaticPath() string
- func (s *Setting) GetWebAppStaticURL() string
- func (s *Setting) GetWebAppType() string
- func (s *Setting) GetWriteTimeoutSecond() int
- type Simpmodel
- type TraceID
- type Trinity
- func (t *Trinity) CleanCache()
- func (t *Trinity) Close()
- func (t *Trinity) GetCache() gcache.Cache
- func (t *Trinity) GetDB() *gorm.DB
- func (t *Trinity) GetGRPCServer() *grpc.Server
- func (t *Trinity) GetLogger() Logger
- func (t *Trinity) GetRouter() *gin.Engine
- func (t *Trinity) GetSetting() ISetting
- func (t *Trinity) GetVCfg() *ViewSetCfg
- func (t *Trinity) InitDatabase()
- func (t *Trinity) Migrate(modelToMigrate ...interface{})
- func (t *Trinity) NewAPIGroup(path string) *gin.RouterGroup
- func (t *Trinity) Serve()
- func (t *Trinity) ServeGRPC()
- func (t *Trinity) ServeHTTP()
- func (t *Trinity) SetCache(cache gcache.Cache) *Trinity
- type UnknownMixin
- type User
- type UserRequestsCtx
- type UserRequestsCtxImpl
- type ViewSetCfg
- type ViewSetRunTime
- type Viewmodel
Constants ¶
const DefaultGRPCHealthCheck string = "/grpc.health.v1.Health/Check"
DefaultGRPCHealthCheck default grpc health check name
const GRPCMethodKey string = "method"
GRPCMethodKey used in passing grpc value
const RFC3339FullDate = "2006-01-02"
RFC3339FullDate for rfc full date
const ReqUserNameKey string = "req_user_name"
ReqUserNameKey used in passing grpc value
const TraceIDKey string = "trace_id"
TraceIDKey used in passing grpc value
Variables ¶
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") )
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 ¶
CheckAccessAuthorization to check access authorization
func CheckFileIsExist ¶ added in v0.0.3
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
ConsulResolverInit init coonsul
func DataVersionFilter ¶ added in v0.0.33
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 ¶
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
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
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 ¶
FilterByParam to filter by param return db
func FilterBySearch ¶
FilterBySearch handle search
func GenerateSnowFlakeID ¶ added in v0.0.33
GenerateSnowFlakeID generate snowflake id
func GenerateToken ¶
GenerateToken generate tokens used for auth
func GetCurrentTime ¶ added in v0.0.40
GetCurrentTime get current time
func GetCurrentTimeString ¶ added in v0.0.40
GetCurrentTimeString get current time with string
func GetCurrentTimeUnix ¶ added in v0.0.40
func GetCurrentTimeUnix() int64
GetCurrentTimeUnix get current time with unix time
func GetRequestType ¶
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
GetServiceName get service name which will register to service mesh
func GetTypeName ¶
GetTypeName to get struct type name
func Getparentdirectory ¶
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 ¶
HandleFilterBackend handle filter backend
func HandlestructBySelect ¶
HandlestructBySelect handling select
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 ¶
JwtAuthBackend check authorization header token is valid
func JwtUnverifiedAuthBackend ¶
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 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
NewEtcdClientConn new etcd client connection
func QueryByOrdering ¶
func QueryByOrdering(c *gin.Context, EnableOrderBy bool, OrderingByList map[string]bool) func(db *gorm.DB) *gorm.DB
QueryByOrdering handle ordering
func QueryByPagination ¶
QueryByPagination handling pagination
func QueryByPreload ¶
QueryByPreload handling preload
func QueryBySelect ¶
QueryBySelect handling select
func RecordErrorLevelTwo ¶
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
SetDefaultWriter set default writer for trinity
func SliceInSlice ¶
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
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 ¶
CheckTokenValid check authorization header token is valid
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
CustomizeSetting for customize setting
type DeleteMixin ¶
type DeleteMixin struct {
ViewSetRunTime *ViewSetRunTime
}
DeleteMixin for Get 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 GlobalSetting ¶ added in v0.0.25
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
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 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 PatchMixin ¶
type PatchMixin struct {
ViewSetRunTime *ViewSetRunTime
}
PatchMixin for Get 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) 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
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
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
GetAllowCredentials get allow credentials
func (*Setting) GetAllowHeaders ¶ added in v1.1.11
GetAllowHeaders get allow headers
func (*Setting) GetAllowMethods ¶ added in v1.1.11
GetAllowMethods get allow method
func (*Setting) GetAllowOrigins ¶ added in v1.1.11
GetAllowOrigins get allow origins
func (*Setting) GetAtomicRequest ¶ added in v1.1.9
GetAtomicRequest get automic request is open
func (*Setting) GetCAPemFile ¶ added in v1.1.7
GetCAPemFile get ca pem file
func (*Setting) GetCacheSize ¶ added in v1.1.11
GetCacheSize get GetCacheSize
func (*Setting) GetCacheTimeout ¶ added in v1.1.11
GetCacheTimeout get GetCacheTimeout
func (*Setting) GetClientKeyFile ¶ added in v1.1.7
GetClientKeyFile get client key file
func (*Setting) GetClientPemFile ¶ added in v1.1.7
GetClientPemFile get client pem file
func (*Setting) GetCorsEnable ¶ added in v1.1.11
GetCorsEnable get if enable cors
func (*Setting) GetDBOption ¶ added in v1.1.11
GetDBOption get db option
func (*Setting) GetDBPassword ¶ added in v1.1.11
GetDBPassword get db password
func (*Setting) GetDbMaxIdleConn ¶ added in v1.1.11
GetDbMaxIdleConn get db max idle connection
func (*Setting) GetDbMaxOpenConn ¶ added in v1.1.11
GetDbMaxOpenConn get db max open connection
func (*Setting) GetDeregisterAfterCritical ¶ added in v1.1.7
GetDeregisterAfterCritical deregister service after critical second
func (*Setting) GetExposeHeaders ¶ added in v1.1.11
GetExposeHeaders get expoose headers
func (*Setting) GetHealthCheckInterval ¶ added in v1.1.7
GetHealthCheckInterval health check interval
func (*Setting) GetIdleTimeoutSecond ¶ added in v1.1.11
GetIdleTimeoutSecond get GetIdleTimeoutSecond
func (*Setting) GetJwtExpireHour ¶ added in v1.1.11
GetJwtExpireHour get GetJwtExpireHour
func (*Setting) GetJwtHeaderPrefix ¶ added in v1.1.11
GetJwtHeaderPrefix get GetJwtHeaderPrefix
func (*Setting) GetJwtIssuer ¶ added in v1.1.11
GetJwtIssuer get GetJwtIssuer
func (*Setting) GetJwtVerifyExpireHour ¶ added in v1.1.11
GetJwtVerifyExpireHour get GetJwtVerifyExpireHour
func (*Setting) GetJwtVerifyIssuer ¶ added in v1.1.11
GetJwtVerifyIssuer get GetJwtVerifyIssuer
func (*Setting) GetLogEnable ¶ added in v1.1.13
GetLogEnable get log enable
func (*Setting) GetLogName ¶ added in v1.1.7
GetLogName get log name
func (*Setting) GetLogRootPath ¶ added in v1.1.7
GetLogRootPath get log root path
func (*Setting) GetMaxAgeHour ¶ added in v1.1.11
GetMaxAgeHour get max age hour
func (*Setting) GetMaxHeaderBytes ¶ added in v1.1.11
GetMaxHeaderBytes get GetMaxHeaderBytes
func (*Setting) GetMigrationPath ¶ added in v1.1.11
GetMigrationPath get GetMigrationPath
func (*Setting) GetPageSize ¶ added in v1.1.11
GetPageSize get GetPageSize
func (*Setting) GetProjectName ¶ added in v1.1.7
GetProjectName get project name
func (*Setting) GetProjectVersion ¶ added in v1.1.7
GetProjectVersion get project name
func (*Setting) GetReadHeaderTimeoutSecond ¶ added in v1.1.11
GetReadHeaderTimeoutSecond get GetReadHeaderTimeoutSecond
func (*Setting) GetReadTimeoutSecond ¶ added in v1.1.11
GetReadTimeoutSecond get readtimeoout
func (*Setting) GetSecretKey ¶ added in v1.1.11
GetSecretKey get GetSecretKey
func (*Setting) GetServerKeyFile ¶ added in v1.1.7
GetServerKeyFile get server key file
func (*Setting) GetServerPemFile ¶ added in v1.1.7
GetServerPemFile get server pem file
func (*Setting) GetServiceMeshAddress ¶ added in v1.1.7
GetServiceMeshAddress get service mesh address
func (*Setting) GetServiceMeshAutoRegister ¶ added in v1.1.11
GetServiceMeshAutoRegister get auto register
func (*Setting) GetServiceMeshPort ¶ added in v1.1.7
GetServiceMeshPort get service mesh port
func (*Setting) GetServiceMeshType ¶ added in v1.1.7
GetServiceMeshType get s m type
func (*Setting) GetSetting ¶ added in v1.1.7
GetSetting get setting
func (*Setting) GetTLSEnabled ¶ added in v1.1.7
GetTLSEnabled get tls enabled
func (*Setting) GetTablePrefix ¶ added in v1.1.11
GetTablePrefix get table prefix
func (*Setting) GetWebAppAddress ¶ added in v1.1.7
GetWebAppAddress get web service ip address
func (*Setting) GetWebAppBaseURL ¶ added in v1.1.11
GetWebAppBaseURL get GetWebAppBaseURL
func (*Setting) GetWebAppMediaPath ¶ added in v1.1.11
GetWebAppMediaPath get web app media path
func (*Setting) GetWebAppMediaURL ¶ added in v1.1.11
GetWebAppMediaURL get web app media url
func (*Setting) GetWebAppPort ¶ added in v1.1.7
GetWebAppPort get web service port
func (*Setting) GetWebAppStaticPath ¶ added in v1.1.11
GetWebAppStaticPath get web app static path
func (*Setting) GetWebAppStaticURL ¶ added in v1.1.11
GetWebAppStaticURL get web app static url
func (*Setting) GetWebAppType ¶ added in v1.1.7
GetWebAppType get web app type
func (*Setting) GetWriteTimeoutSecond ¶ added in v1.1.11
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 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) GetGRPCServer ¶ added in v1.1.7
GetGRPCServer get grpc server instance
func (*Trinity) GetSetting ¶ added in v0.0.10
GetSetting get setting
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
type UnknownMixin ¶
type UnknownMixin struct {
ViewSetRunTime *ViewSetRunTime
}
UnknownMixin for Get 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 (*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
Source Files ¶
- ViewSetCfg.go
- backend_access.go
- backend_filter.go
- cache.go
- constant.go
- context.go
- db.go
- error.go
- grpc_pool.go
- init_migrate.go
- init_migration.go
- interceptor.go
- logger.go
- logger_formatter.go
- middleware_jwt.go
- middleware_logger.go
- miiddleware_timeout.go
- model_appchangelog.go
- model_apperror.go
- model_common.go
- model_group.go
- model_permission.go
- model_role.go
- model_user.go
- query_filter.go
- query_orderby.go
- query_pagination.go
- query_preload.go
- query_select.go
- router.go
- service_delete.go
- service_discovery.go
- service_get.go
- service_handler.go
- service_mesh.go
- service_patch.go
- service_post.go
- service_put.go
- service_response.go
- service_retrieve.go
- setting.go
- trinity.go
- utils.go
- viewset.go