Documentation
¶
Index ¶
- Variables
- func CheckAccessAuthorization(requiredPermission, userPermission []string) error
- func CreateResource(r *PostMixin)
- func CustomizeLogFormatter(params LogFormatterParams) string
- func DefaultAccessBackend(v *ViewSetRunTime) error
- func DefaultFilterBackend(c *gin.Context, db *gorm.DB) *gorm.DB
- func DeleteResource(r *DeleteMixin)
- func FilterByFilter(c *gin.Context, FilterByList []string, ...) func(db *gorm.DB) *gorm.DB
- func FilterByParam(param string) func(db *gorm.DB) *gorm.DB
- func FilterBySearch(c *gin.Context, SearchingByList []string) func(db *gorm.DB) *gorm.DB
- func FilterKeyByParam(param string) func(db *gorm.DB) *gorm.DB
- func FilterPidByParam(param string) func(db *gorm.DB) *gorm.DB
- func GenerateToken(userkey string) (string, error)
- func GetRequestType(c *gin.Context) string
- func GetResourceByid(r *RetrieveMixin)
- func GetResourceList(r *GetMixin)
- func GetTypeName(myvar interface{}) string
- func HandleFilterBackend(v *ViewSetCfg, method string, c *gin.Context) func(db *gorm.DB) *gorm.DB
- func HandleServices(m ReqMixinHandler, v *ViewSetRunTime, cHandler ...func(r *ViewSetRunTime))
- func HandlestructBySelect(c *gin.Context, resource interface{}) (int, interface{}, error)
- func InSlice(value string, stringSlice []string) bool
- func JWT() gin.HandlerFunc
- func JwtAuthBackend(c *gin.Context) error
- func JwtUnverifiedAuthBackend(c *gin.Context) error
- func LoggerWithConfig(conf LoggerConfig) gin.HandlerFunc
- func LoggerWithFormatter() gin.HandlerFunc
- func MigrateModel(funcToMigrateDB func(interface{}), funcToCreatePermission func([]string), ...)
- func PatchResource(r *PatchMixin)
- func QueryByOrdering(c *gin.Context, 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 []string) func(db *gorm.DB) *gorm.DB
- func QueryBySelect(c *gin.Context) func(db *gorm.DB) *gorm.DB
- func RecordErrorLevelTwo() (uintptr, string, int)
- func RegisterRestStyleRouter(r *gin.RouterGroup, resource string, viewset gin.HandlerFunc, ...)
- func SliceInSlice(sliceToCheck []string, slice []string) bool
- type Claims
- type DeleteMixin
- type FedidClaims
- type GetMixin
- type LogFormat
- type LogFormatter
- type LogFormatterParams
- type Logger
- type LoggerConfig
- type PatchMixin
- type PostMixin
- type PutMixin
- type ReqMixinHandler
- type ResponseData
- type RetrieveMixin
- type UnknownMixin
- type ViewSetCfg
- type ViewSetRunTime
Constants ¶
This section is empty.
Variables ¶
var ( // DefaultJwtexpirehour for jwt DefaultJwtexpirehour = 2 // DefaultJwtheaderprefix for jwt DefaultJwtheaderprefix = "Mold" // DefaultSecretkey for jwt DefaultSecretkey = "234" // DefaultJwtissuer for jwt DefaultJwtissuer = "Mold" // DefaultAppVersion for logging middleware DefaultAppVersion = "v1.0" // DefaultProjectName for logging middleware DefaultProjectName = "grf" //DefaultLogger set default logger DefaultLogger = &log{} )
Functions ¶
func CheckAccessAuthorization ¶
CheckAccessAuthorization to check access authorization
func CustomizeLogFormatter ¶
func CustomizeLogFormatter(params LogFormatterParams) string
CustomizeLogFormatter for customize log format
func DefaultAccessBackend ¶
func DefaultAccessBackend(v *ViewSetRunTime) error
DefaultAccessBackend for Mixin
func DefaultFilterBackend ¶
DefaultFilterBackend for Mixin
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 FilterKeyByParam ¶
FilterKeyByParam filter key by param
func FilterPidByParam ¶
FilterPidByParam filter pid by param
func GenerateToken ¶
GenerateToken generate tokens used for auth
func GetRequestType ¶
GetRequestType to get http request type with restful style
func HandleFilterBackend ¶
HandleFilterBackend handle filter backend
func HandleServices ¶ added in v1.1.5
func HandleServices(m ReqMixinHandler, v *ViewSetRunTime, cHandler ...func(r *ViewSetRunTime))
HandleServices for multi response
func HandlestructBySelect ¶
HandlestructBySelect handling select
func JwtAuthBackend ¶
JwtAuthBackend check authorization header token is valid
func JwtUnverifiedAuthBackend ¶
JwtUnverifiedAuthBackend get claim info
func LoggerWithConfig ¶
func LoggerWithConfig(conf LoggerConfig) gin.HandlerFunc
LoggerWithConfig instance a Logger middleware with config.
func LoggerWithFormatter ¶
func LoggerWithFormatter() gin.HandlerFunc
LoggerWithFormatter instance a Logger middleware with the specified log format function.
func MigrateModel ¶
func MigrateModel(funcToMigrateDB func(interface{}), funcToCreatePermission func([]string), modelToMigrate ...interface{})
MigrateModel to migrate model
func QueryByOrdering ¶
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 RegisterRestStyleRouter ¶
func RegisterRestStyleRouter(r *gin.RouterGroup, resource string, viewset gin.HandlerFunc, SupportedMethod []string)
RegisterRestStyleRouter to register rest style router
func SliceInSlice ¶
SliceInSlice if slice in slice
Types ¶
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 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 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"`
UID string `json:"uid"`
}
LogFormat log format struct
type LogFormatter ¶
type LogFormatter func(params LogFormatterParams) string
LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter
type LogFormatterParams ¶
type LogFormatterParams struct {
Request *http.Request
// TimeStamp shows the time after the server returns a response.
TimeStamp time.Time
// StatusCode is HTTP response code.
StatusCode int
// Latency is how much time the server cost to process a certain request.
Latency time.Duration
// ClientIP equals Context's ClientIP method.
ClientIP string
// Method is the HTTP method given to the request.
Method string
// Path is a path the client requests.
Path string
// ErrorMessage is set if error has occurred in processing the request.
ErrorMessage string
// Error Detail
ErrorDetail string
// BodySize is the size of the Response Body
BodySize int
// Keys are the keys set on the request's context.
Keys map[string]interface{}
// UserID is the request user
UserID string
// request TraceID unique
TraceID string
// contains filtered or unexported fields
}
LogFormatterParams is the structure any formatter will be handed when time to log comes
type Logger ¶ added in v1.1.4
type Logger interface {
LogWriter(v *ViewSetRunTime)
}
Logger to record log
type LoggerConfig ¶
type LoggerConfig struct {
// Optional. Default value is gin.defaultLogFormatter
Formatter LogFormatter
// Output is a writer where logs are written.
// Optional. Default value is gin.DefaultWriter.
Output io.Writer
// SkipPaths is a url path array which logs are not written.
// Optional.
SkipPaths []string
}
LoggerConfig defines the config for Logger middleware.
type ReqMixinHandler ¶
type ReqMixinHandler interface {
Handler()
}
ReqMixinHandler for handle mixin
type ResponseData ¶ added in v1.1.4
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
}
RetrieveMixin for Get request
func (*RetrieveMixin) Handler ¶
func (r *RetrieveMixin) Handler()
Handler for handle retrieve request
type ViewSetCfg ¶
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 : grf.CheckAccessAuthorization(requiredPermission , userPermission) , true?allow:deny
AccessBackendCheckMap map[string]func(v *ViewSetRunTime) error
// PreloadListMap gorm preload list
PreloadListMap map[string][]string
// 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)
// Get: customize Get func
Get func(r *ViewSetRunTime)
// Post: customize Post func
Post func(r *ViewSetRunTime)
// Put: customize Put func
Put func(r *ViewSetRunTime)
// Patch: customize Patch func
Patch func(r *ViewSetRunTime)
// Delete: customize Delete func
Delete func(r *ViewSetRunTime)
// Logger
Logger Logger
}
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
type ViewSetRunTime ¶
type ViewSetRunTime struct {
Method string
// gin.context
Gcontext *gin.Context
// db instance
Db *gorm.DB
// ResourceModel
// target resource model
ResourceModel interface{} // ResourceModel for the resource
// 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 interface{}
AccessBackendRequire []string
AccessBackendCheck func(v *ViewSetRunTime) error
DBFilterBackend func(db *gorm.DB) *gorm.DB // current dbfilterbackend
PreloadList []string
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
Retrieve func(r *ViewSetRunTime)
Get func(r *ViewSetRunTime)
Post func(r *ViewSetRunTime)
Put func(r *ViewSetRunTime)
Patch func(r *ViewSetRunTime)
Delete func(r *ViewSetRunTime)
Cfg *ViewSetCfg
//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 ¶ added in v1.1.5
func (v *ViewSetRunTime) Response()
Response handle grf 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