grf

package module
v1.1.6 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2019 License: MIT Imports: 16 Imported by: 0

README

grf

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

安装

打开终端输入

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

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 : 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) *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;"`
}

*初始化grf设置

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


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

	GlobalViewSet = grf.InitDefault(db.Dsource)

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

  • 使用log,jwt中间件及注册路由
func Router() *gin.Engine {
    r := gin.New()
    ````
    r.Use(grf.JWT())                 // jwt中间件
    r.Use(grf.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)
        grf.RegisterRestStyleRouter(v1, "users", servicev1.UserViewSet, []string{"Retrieve", "List", "Create", "Update", "Delete"})
    }
    ```
  • 注册路由处理
// CountryViewSet hanlde router
func CountryViewSet(c *gin.Context) {
	v := grfinit.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())
}
  • 支持关键字

    • 过滤 (系统预置关键字)
	
	//Example :http://127.0.0.1/countries?xxx__like=ooo&xxx__ilike=ooo&xxx__start=date1
	----FilterByList   filter condition must configured in FilterByList config  
	// v.FilterByList=[]string{"xxx__like","xxx__ilike"}
	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  
	xxx__end=date2		=> xxx < date2
	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 ,'') !='' )  
	xxxhasoraaa=fff		=> (xxx = fff or aaa = fff)
	xxx=ooo			=>xxx = ooo
  • 自定义过滤 (自定义关键字和查询方法)
	#Example  :http://127.0.0.1/countries?filterpolarpanda=me
	----FilterByList   filter condition must configured in FilterByList config  
	// v.FilterByList=[]string{"filterpolarpanda"}
	// v.FilterCustomizeFunc=map[string]func(db *gorm.DB, queryValue string) *gorm.DB{
		"filterpolarpanda":func(db *gorm.DB, queryValue string) *gorm.DB{
			db.Where("polarpanda = ?" , "me")
		}
	}
	filterpolarpanda=me 		=> polarpanda = 'me'  
	
  • 自定义搜索 (自定义关键字集合)
	#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    
  • 自定义分页 (自定义分页数量和页码)
	//默认开启分页
	#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 grf 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

}

to do list :

支持字段级验证请求数据
外键字段过滤
gorm日志链路追踪

Documentation

Index

Constants

This section is empty.

Variables

View Source
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

func CheckAccessAuthorization(requiredPermission, userPermission []string) error

CheckAccessAuthorization to check access authorization

func CreateResource

func CreateResource(r *PostMixin)

CreateResource : Create method

func CustomizeLogFormatter

func CustomizeLogFormatter(params LogFormatterParams) string

CustomizeLogFormatter for customize log format

func DefaultAccessBackend

func DefaultAccessBackend(v *ViewSetRunTime) error

DefaultAccessBackend for Mixin

func DefaultFilterBackend

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

DefaultFilterBackend for Mixin

func DeleteResource

func DeleteResource(r *DeleteMixin)

DeleteResource : DELETE method

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 string) 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 FilterKeyByParam

func FilterKeyByParam(param string) func(db *gorm.DB) *gorm.DB

FilterKeyByParam filter key by param

func FilterPidByParam

func FilterPidByParam(param string) func(db *gorm.DB) *gorm.DB

FilterPidByParam filter pid by param

func GenerateToken

func GenerateToken(userkey string) (string, error)

GenerateToken generate tokens used for auth

func GetRequestType

func GetRequestType(c *gin.Context) string

GetRequestType to get http request type with restful style

func GetResourceByid

func GetResourceByid(r *RetrieveMixin)

GetResourceByid : Retrieve method

func GetResourceList

func GetResourceList(r *GetMixin)

GetResourceList : List method

func GetTypeName

func GetTypeName(myvar interface{}) string

GetTypeName to get struct type name

func HandleFilterBackend

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

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

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 JWT

func JWT() gin.HandlerFunc

JWT is jwt middleware

func JwtAuthBackend

func JwtAuthBackend(c *gin.Context) error

JwtAuthBackend check authorization header token is valid

func JwtUnverifiedAuthBackend

func JwtUnverifiedAuthBackend(c *gin.Context) error

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 PatchResource

func PatchResource(r *PatchMixin)

PatchResource : PATCH method

func QueryByOrdering

func QueryByOrdering(c *gin.Context, 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 []string) 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 RegisterRestStyleRouter

func RegisterRestStyleRouter(r *gin.RouterGroup, resource string, viewset gin.HandlerFunc, SupportedMethod []string)

RegisterRestStyleRouter to register rest style router

func SliceInSlice

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

SliceInSlice if slice in slice

Types

type Claims

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

Claims data to sign

func CheckTokenValid

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

CheckTokenValid check authorization header token is valid

func ParseToken

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

ParseToken parsing token

type DeleteMixin

type DeleteMixin struct {
	*ViewSetRunTime
}

DeleteMixin for Get request

func (*DeleteMixin) Handler

func (r *DeleteMixin) Handler()

Handler for handle delete request

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 GetMixin

type GetMixin struct {
	*ViewSetRunTime
}

GetMixin for Get request

func (*GetMixin) Handler

func (r *GetMixin) Handler()

Handler for handle retrieve request

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 PatchMixin

type PatchMixin struct {
	*ViewSetRunTime
}

PatchMixin for Get request

func (*PatchMixin) Handler

func (r *PatchMixin) Handler()

Handler for handle patch request

type PostMixin

type PostMixin struct {
	*ViewSetRunTime
}

PostMixin for Get request

func (*PostMixin) Handler

func (r *PostMixin) Handler()

Handler for handle post request

type PutMixin

type PutMixin struct {
	*ViewSetRunTime
}

PutMixin for Get request

func (*PutMixin) Handler

func (r *PutMixin) Handler()

Handler for handle put request

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 UnknownMixin

type UnknownMixin struct {
	*ViewSetRunTime
}

UnknownMixin for Get request

func (*UnknownMixin) Handler

func (r *UnknownMixin) Handler()

Handler for handle Unknown 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 InitDefault

func InitDefault(db *gorm.DB) *ViewSetCfg

InitDefault for initial ViewSetCfg

func (*ViewSetCfg) New

func (v *ViewSetCfg) New() *ViewSetCfg

New default cfg

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

Jump to

Keyboard shortcuts

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