carrot

package module
v0.0.0-...-50939d4 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2024 License: BSD-3-Clause Imports: 44 Imported by: 4

README

carrot - restsend golang library

Description

Carrot is a golang library for simplifying backend develop. Builtin with a simple admin panel for developer. (Use alpinejs for the frontend framework)

  • Admin list page image
  • Admin edit page image
Quick start

See the examples directory for a quick start.

Documentation

Index

Constants

View Source
const (
	UserField      = "_carrot_uid"
	GroupField     = "_carrot_gid"
	DbField        = "_carrot_db"
	TzField        = "_carrot_tz"
	AssetsField    = "_carrot_assets"
	TemplatesField = "_carrot_templates"
)
View Source
const (
	PermissionAll    = "all"
	PermissionCreate = "create"
	PermissionUpdate = "update"
	PermissionRead   = "read"
	PermissionDelete = "delete"
)
View Source
const (
	GroupRoleAdmin  = "admin"
	GroupRoleMember = "member"
)
View Source
const (
	GroupTypeAdmin = "admin" // carrot admin, for /admin path with permissions check
	GroupTypeApp   = "app"
)
View Source
const (
	ConfigFormatJSON     = "json"
	ConfigFormatYAML     = "yaml"
	ConfigFormatInt      = "int"
	ConfigFormatFloat    = "float"
	ConfigFormatBool     = "bool"
	ConfigFormatText     = "text"
	ConfigFormatSecurity = "security"
	ConfigFormatDate     = "date"
	ConfigFormatDatetime = "datetime"
	ConfigFormatDuration = "duration"
)
View Source
const (
	FilterOpIsNot          = "is not"
	FilterOpEqual          = "="
	FilterOpNotEqual       = "<>"
	FilterOpIn             = "in"
	FilterOpNotIn          = "not_in"
	FilterOpGreater        = ">"
	FilterOpGreaterOrEqual = ">="
	FilterOpLess           = "<"
	FilterOpLessOrEqual    = "<="
	FilterOpLike           = "like"
	FilterOpBetween        = "between"
)
View Source
const (
	OrderOpDesc = "desc"
	OrderOpAsc  = "asc"
)
View Source
const (
	GET    = 1 << 1
	CREATE = 1 << 2
	EDIT   = 1 << 3
	DELETE = 1 << 4
	QUERY  = 1 << 5
)
View Source
const (
	//SigUserLogin: user *User, c *gin.Context
	SigUserLogin = "user.login"
	//SigUserLogout: user *User, c *gin.Context
	SigUserLogout = "user.logout"
	//SigUserCreate: user *User, c *gin.Context
	SigUserCreate = "user.create"
	//SigUserVerifyEmail: user *User, hash, clientIp, userAgent string
	SigUserVerifyEmail = "user.verifyemail"
	//SigUserResetPassword: user *User, hash, clientIp, userAgent string
	SigUserResetPassword = "user.resetpassword"
	//SigUserResetPassword: user *User, hash, clientIp, userAgent, newEmail string
	SigUserChangeEmail = "user.changeemail"
)
View Source
const CORS_ALLOW_ALL = "*"

Cors

View Source
const CORS_ALLOW_CREDENTIALS = "true"
View Source
const CORS_ALLOW_HEADERS = "" /* 137-byte string literal not displayed */
View Source
const CORS_ALLOW_METHODS = "POST, OPTIONS, GET, PUT, PATCH, DELETE"
View Source
const (
	DefaultQueryLimit = 102400 // 100k
)
View Source
const ENV_AUTH_PREFIX = "AUTH_PREFIX"
View Source
const ENV_CONFIG_CACHE_EXPIRED = "CONFIG_CACHE_EXPIRED"

Default Value: 10s

View Source
const ENV_CONFIG_CACHE_SIZE = "CONFIG_CACHE_SIZE"

Default Value: 1024

View Source
const ENV_DB_DRIVER = "DB_DRIVER"

DB

View Source
const ENV_DSN = "DSN"
View Source
const ENV_SALT = "PASSWORD_SALT"

User Password salt

View Source
const ENV_SESSION_EXPIRE_DAYS = "SESSION_EXPIRE_DAYS"
View Source
const ENV_SESSION_FIELD = "SESSION_FIELD"

Gin session field name

View Source
const ENV_SESSION_SECRET = "SESSION_SECRET"

Session

View Source
const ENV_STATIC_PREFIX = "STATIC_PREFIX"
View Source
const ENV_STATIC_ROOT = "STATIC_ROOT"
View Source
const ENV_TEMPLATE_ROOT = "TEMPLATE_ROOT"
View Source
const KEY_ADMIN_DASHBOARD = "ADMIN_DASHBOARD"
View Source
const KEY_AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED"
View Source
const KEY_RESET_PASSWD_EXPIRED = "RESET_PASSWD_EXPIRED"
View Source
const KEY_SITE_ADMIN = "SITE_ADMIN"
View Source
const KEY_SITE_CHANGE_EMAIL_DONE_API = "SITE_CHANGE_EMAIL_DONE_API"
View Source
const KEY_SITE_COPYRIGHT = "SITE_COPYRIGHT"
View Source
const KEY_SITE_DESCRIPTION = "SITE_DESCRIPTION"
View Source
const KEY_SITE_FAVICON_URL = "SITE_FAVICON_URL"
View Source
const KEY_SITE_GA = "SITE_GA"
View Source
const KEY_SITE_KEYWORDS = "SITE_KEYWORDS"
View Source
const KEY_SITE_LOGIN_NEXT = "SITE_LOGIN_NEXT"
View Source
const KEY_SITE_LOGOUT_URL = "SITE_LOGOUT_URL"
View Source
const KEY_SITE_LOGO_URL = "SITE_LOGO_URL"
View Source
const KEY_SITE_NAME = "SITE_NAME"
View Source
const KEY_SITE_PRIVACY_URL = "SITE_PRIVACY_URL"
View Source
const KEY_SITE_RESET_PASSWORD_DONE_API = "SITE_RESET_PASSWORD_DONE_API"
View Source
const KEY_SITE_RESET_PASSWORD_URL = "SITE_RESET_PASSWORD_URL"
View Source
const KEY_SITE_SIGNIN_API = "SITE_SIGNIN_API"
View Source
const KEY_SITE_SIGNIN_URL = "SITE_SIGNIN_URL"
View Source
const KEY_SITE_SIGNUP_API = "SITE_SIGNUP_API"
View Source
const KEY_SITE_SIGNUP_URL = "SITE_SIGNUP_URL"
View Source
const KEY_SITE_TERMS_URL = "SITE_TERMS_URL"
View Source
const KEY_SITE_URL = "SITE_URL"
View Source
const KEY_SITE_USER_ID_TYPE = "SITE_USER_ID_TYPE"
View Source
const KEY_USER_ACTIVATED = "USER_ACTIVATED"
View Source
const KEY_VERIFY_EMAIL_EXPIRED = "VERIFY_EMAIL_EXPIRED"

Variables

View Source
var DefaultAuthPrefix = "/auth"
View Source
var DefaultMemorySessionKeyLength = 32
View Source
var EmbedStaticAssets embed.FS
View Source
var EmbedTemplates embed.FS
View Source
var ErrBadToken = errors.New("bad token")
View Source
var ErrEmailExists = errors.New("email exists, please use another email")
View Source
var ErrEmailRequired = errors.New("email required")
View Source
var ErrEmptyEmail = errors.New("empty email")
View Source
var ErrEmptyPassword = errors.New("empty password")
View Source
var ErrForbidden = errors.New("forbidden access")
View Source
var ErrInvalidPrimaryKey = errors.New("invalid primary key")
View Source
var ErrInvalidToken = errors.New("invalid token")
View Source
var ErrInvalidView = errors.New("with invalid view")
View Source
var ErrNotActivated = errors.New("user not activated")
View Source
var ErrNotChanged = errors.New("not changed")
View Source
var ErrNotFound = errors.New("not found")
View Source
var ErrOnlySuperUser = errors.New("only super user can do this")
View Source
var ErrSameEmail = errors.New("same email")
View Source
var ErrTokenExpired = errors.New("token expired")
View Source
var ErrTokenRequired = errors.New("token required")
View Source
var ErrUnauthorized = errors.New("unauthorized")
View Source
var ErrUserNotAllowLogin = errors.New("user not allow login")
View Source
var ErrUserNotExists = errors.New("user not exists")

Functions

func AbortWithJSONError

func AbortWithJSONError(c *gin.Context, code int, err error)

func AuthRequired

func AuthRequired(c *gin.Context)

func BuildAuthToken

func BuildAuthToken(db *gorm.DB, user *User, expired time.Duration, useLoginTime bool) string

Build a token for user. If useLoginTime is true, the token will be expired after user login.

func CORSEnabled

func CORSEnabled() gin.HandlerFunc

func ChangeUserEmail

func ChangeUserEmail(db *gorm.DB, user *User, newEmail string) error

func CheckPassword

func CheckPassword(user *User, password string) bool

func CheckUserAllowLogin

func CheckUserAllowLogin(db *gorm.DB, user *User) error

func CheckValue

func CheckValue(db *gorm.DB, key, defaultValue, format string, autoload, public bool)

func CurrentTimezone

func CurrentTimezone(c *gin.Context) *time.Location

func DeactiveUser

func DeactiveUser(db *gorm.DB, user *User) error

func EncodeHashToken

func EncodeHashToken(user *User, timestamp int64, useLastlogin bool) (hash string)

func FormatSizeHuman

func FormatSizeHuman(size float64) string

func GenUniqueKey

func GenUniqueKey(tx *gorm.DB, field string, size int) (key string)

GenUniqueKey generate a unique value for a field in a table.

func GetBoolEnv

func GetBoolEnv(key string) bool

func GetBoolValue

func GetBoolValue(db *gorm.DB, key string) bool

func GetCarrotSessionField

func GetCarrotSessionField() string

func GetEnv

func GetEnv(key string) string

func GetIntEnv

func GetIntEnv(key string) int64

func GetIntValue

func GetIntValue(db *gorm.DB, key string, defaultVal int) int

func GetRenderPageContext

func GetRenderPageContext(c *gin.Context) map[string]any

func GetValue

func GetValue(db *gorm.DB, key string) string

func HandleAdminJson

func HandleAdminJson(c *gin.Context, objects []*AdminObject, buildContext AdminBuildContext)

func HashPassword

func HashPassword(password string) string

func HintAssetsRoot

func HintAssetsRoot(dirName string) string

func InTimezone

func InTimezone(c *gin.Context, timezone string)

func InitAuthHandler

func InitAuthHandler(authRoutes gin.IRoutes)

func InitCarrot

func InitCarrot(db *gorm.DB, r *gin.Engine) (err error)

func InitDatabase

func InitDatabase(logWrite io.Writer, driver, dsn string) (*gorm.DB, error)

func InitMigrate

func InitMigrate(db *gorm.DB) error

func IsExistsByEmail

func IsExistsByEmail(db *gorm.DB, email string) bool

func LoadAutoloads

func LoadAutoloads(db *gorm.DB)

func LoadEnvs

func LoadEnvs(objPtr any)

load envs to struct

func Login

func Login(c *gin.Context, user *User)

func Logout

func Logout(c *gin.Context, user *User)

func LookupEnv

func LookupEnv(key string) (value string, found bool)

func MakeMigrates

func MakeMigrates(db *gorm.DB, insts []any) error

func NewTemplateFuncs

func NewTemplateFuncs() template.FuncMap

func RandNumberText

func RandNumberText(n int) string

func RandText

func RandText(n int) string

func RegisterAdmins

func RegisterAdmins(r *gin.RouterGroup, db *gorm.DB, objs []AdminObject)

RegisterAdmins registers admin routes

func RegisterObject

func RegisterObject(r *gin.RouterGroup, obj *WebObject) error

func RegisterObjects

func RegisterObjects(r *gin.RouterGroup, objs []WebObject)

func SanitizeSensitiveValues

func SanitizeSensitiveValues(prefix string, data any) map[string]any

func SetGroupExtra

func SetGroupExtra(db *gorm.DB, group *Group, key string, value string) error

func SetGroupMemberExtra

func SetGroupMemberExtra(db *gorm.DB, member *GroupMember, key string, value string) error

func SetLastLogin

func SetLastLogin(db *gorm.DB, user *User, lastIp string) error

func SetPassword

func SetPassword(db *gorm.DB, user *User, password string) (err error)

func SetValue

func SetValue(db *gorm.DB, key, value, format string, autoload, public bool)

func SwitchGroup

func SwitchGroup(c *gin.Context, group *Group)

func UpdateUserFields

func UpdateUserFields(db *gorm.DB, user *User, vals map[string]any) error

func WithAdminAuth

func WithAdminAuth() gin.HandlerFunc

func WithCORS

func WithCORS(origin, credentials, headers, methods string) gin.HandlerFunc

func WithCookieSession

func WithCookieSession(secret string, maxAge int) gin.HandlerFunc

func WithGormDB

func WithGormDB(db *gorm.DB) gin.HandlerFunc

func WithHandleStatic

func WithHandleStatic(staticPrefix, staticDir string) gin.HandlerFunc

func WithMemSession

func WithMemSession(secret string) gin.HandlerFunc

func WithStaticAssets

func WithStaticAssets(r *gin.Engine, staticPrefix, staticRootDir string) gin.HandlerFunc

func WithTemplates

func WithTemplates(r *gin.Engine, templateRootDir string) gin.HandlerFunc

Types

type AdminAccessCheck

type AdminAccessCheck func(c *gin.Context, obj *AdminObject) error

Access control

type AdminAction

type AdminAction struct {
	Path          string             `json:"path"`
	Name          string             `json:"name"`
	Label         string             `json:"label,omitempty"`
	Icon          string             `json:"icon,omitempty"`
	Class         string             `json:"class,omitempty"`
	WithoutObject bool               `json:"withoutObject"`
	Batch         bool               `json:"batch,omitempty"`
	Handler       AdminActionHandler `json:"-"`
}

type AdminActionHandler

type AdminActionHandler func(db *gorm.DB, c *gin.Context, obj any) (bool, any, error)

type AdminAttribute

type AdminAttribute struct {
	Default      any                 `json:"default,omitempty"`
	Choices      []AdminSelectOption `json:"choices,omitempty"`
	SingleChoice bool                `json:"singleChoice,omitempty"`
	Widget       string              `json:"widget,omitempty"`
	FilterWidget string              `json:"filterWidget,omitempty"`
	Help         string              `json:"help,omitempty"`
}

type AdminBuildContext

type AdminBuildContext func(*gin.Context, map[string]any) map[string]any

type AdminField

type AdminField struct {
	Placeholder string          `json:"placeholder,omitempty"` // Placeholder of the filed
	Label       string          `json:"label"`                 // Label of the filed
	NotColumn   bool            `json:"notColumn,omitempty"`   // Not a column
	Required    bool            `json:"required,omitempty"`
	Name        string          `json:"name"`
	Type        string          `json:"type"`
	Tag         string          `json:"tag,omitempty"`
	Attribute   *AdminAttribute `json:"attribute,omitempty"`
	CanNull     bool            `json:"canNull,omitempty"`
	IsArray     bool            `json:"isArray,omitempty"`
	Primary     bool            `json:"primary,omitempty"`
	Foreign     *AdminForeign   `json:"foreign,omitempty"`
	IsAutoID    bool            `json:"isAutoId,omitempty"`
	IsPtr       bool            `json:"isPtr,omitempty"`
	// contains filtered or unexported fields
}

type AdminForeign

type AdminForeign struct {
	Path  string `json:"path"`
	Field string `json:"field"`
	// contains filtered or unexported fields
}

type AdminIcon

type AdminIcon struct {
	Url string `json:"url,omitempty"`
	SVG string `json:"svg,omitempty"`
}

type AdminObject

type AdminObject struct {
	Model       any             `json:"-"`
	Group       string          `json:"group"`               // Group name
	Name        string          `json:"name"`                // Name of the object
	Desc        string          `json:"desc,omitempty"`      // Description
	Path        string          `json:"path"`                // Path prefix
	Shows       []string        `json:"shows"`               // Show fields
	Orders      []Order         `json:"orders"`              // Default orders of the object
	Editables   []string        `json:"editables"`           // Editable fields
	Filterables []string        `json:"filterables"`         // Filterable fields
	Orderables  []string        `json:"orderables"`          // Orderable fields, can override Orders
	Searchables []string        `json:"searchables"`         // Searchable fields
	Requireds   []string        `json:"requireds,omitempty"` // Required fields
	PrimaryKeys []string        `json:"primaryKeys"`         // Primary keys name
	UniqueKeys  []string        `json:"uniqueKeys"`          // Primary keys name
	PluralName  string          `json:"pluralName"`
	Fields      []AdminField    `json:"fields"`
	EditPage    string          `json:"editpage,omitempty"`
	ListPage    string          `json:"listpage,omitempty"`
	Scripts     []AdminScript   `json:"scripts,omitempty"`
	Styles      []string        `json:"styles,omitempty"`
	Permissions map[string]bool `json:"permissions,omitempty"`
	Actions     []AdminAction   `json:"actions,omitempty"`
	Icon        *AdminIcon      `json:"icon,omitempty"`
	Invisible   bool            `json:"invisible,omitempty"`
	ViewOnSite  AdminViewOnSite `json:"-"`

	Attributes   map[string]AdminAttribute `json:"-"` // Field's extra attributes
	AccessCheck  AdminAccessCheck          `json:"-"` // Access control function
	GetDB        GetDB                     `json:"-"`
	BeforeCreate BeforeCreateFunc          `json:"-"`
	BeforeRender BeforeRenderFunc          `json:"-"`
	BeforeUpdate BeforeUpdateFunc          `json:"-"`
	BeforeDelete BeforeDeleteFunc          `json:"-"`
	// contains filtered or unexported fields
}

func BuildAdminObjects

func BuildAdminObjects(r *gin.RouterGroup, db *gorm.DB, objs []AdminObject) []*AdminObject

func GetCarrotAdminObjects

func GetCarrotAdminObjects() []AdminObject

Returns all admin objects

func (*AdminObject) Build

func (obj *AdminObject) Build(db *gorm.DB) error

Build fill the properties of obj.

func (*AdminObject) BuildPermissions

func (obj *AdminObject) BuildPermissions(db *gorm.DB, user *User)

func (*AdminObject) MarshalOne

func (obj *AdminObject) MarshalOne(c *gin.Context, val interface{}) (map[string]any, error)

func (*AdminObject) QueryObjects

func (obj *AdminObject) QueryObjects(session *gorm.DB, form *QueryForm, ctx *gin.Context) (r AdminQueryResult, err error)

func (*AdminObject) RegisterAdmin

func (obj *AdminObject) RegisterAdmin(r gin.IRoutes)

RegisterAdmin registers admin routes

  • POST /admin/{objectslug} -> Query objects
  • PUT /admin/{objectslug} -> Create One
  • PATCH /admin/{objectslug}} -> Update One
  • DELETE /admin/{objectslug} -> Delete One
  • POST /admin/{objectslug}/:name -> Action

func (*AdminObject) UnmarshalFrom

func (obj *AdminObject) UnmarshalFrom(elemObj reflect.Value, keys, vals map[string]any) (any, error)

type AdminQueryResult

type AdminQueryResult struct {
	TotalCount int              `json:"total,omitempty"`
	Pos        int              `json:"pos,omitempty"`
	Limit      int              `json:"limit,omitempty"`
	Keyword    string           `json:"keyword,omitempty"`
	Items      []map[string]any `json:"items"`
	// contains filtered or unexported fields
}

type AdminScript

type AdminScript struct {
	Src    string `json:"src"`
	Onload bool   `json:"onload,omitempty"`
}

type AdminSelectOption

type AdminSelectOption struct {
	Label string `json:"label"`
	Value any    `json:"value"`
}

type AdminValue

type AdminValue struct {
	Value any    `json:"value"`
	Label string `json:"label,omitempty"`
}

type AdminViewOnSite

type AdminViewOnSite func(db *gorm.DB, c *gin.Context, obj any) string

type AvgUsage

type AvgUsage struct {
	Threshold time.Duration
	StartAt   time.Time
	// contains filtered or unexported fields
}

func (*AvgUsage) Add

func (at *AvgUsage) Add(v time.Duration)

func (*AvgUsage) CountPerMinute

func (at *AvgUsage) CountPerMinute() float64

func (*AvgUsage) Get

func (at *AvgUsage) Get() time.Duration

func (*AvgUsage) GetCount

func (at *AvgUsage) GetCount() int

type BeforeCreateFunc

type BeforeCreateFunc func(db *gorm.DB, ctx *gin.Context, vptr any) error

type BeforeDeleteFunc

type BeforeDeleteFunc func(db *gorm.DB, ctx *gin.Context, vptr any) error

type BeforeQueryRenderFunc

type BeforeQueryRenderFunc func(db *gorm.DB, ctx *gin.Context, r *QueryResult) (any, error)

type BeforeRenderFunc

type BeforeRenderFunc func(db *gorm.DB, ctx *gin.Context, vptr any) (any, error)

type BeforeUpdateFunc

type BeforeUpdateFunc func(db *gorm.DB, ctx *gin.Context, vptr any, vals map[string]any) error

type ChangeEmailDoneForm

type ChangeEmailDoneForm struct {
	Password string `json:"password" form:"password"`
	Email    string `json:"email" form:"email" binding:"required"`
	Token    string `json:"token" form:"token" binding:"required"`
}

type ChangePasswordForm

type ChangePasswordForm struct {
	Password string `json:"password" binding:"required"`
}

type CombineEmbedFS

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

func NewCombineEmbedFS

func NewCombineEmbedFS(assertDir string, es ...EmbedFS) *CombineEmbedFS

func (*CombineEmbedFS) Open

func (c *CombineEmbedFS) Open(name string) (fs.File, error)

func (*CombineEmbedFS) ReadDir

func (c *CombineEmbedFS) ReadDir(name string) ([]fs.DirEntry, error)

type CombineTemplates

type CombineTemplates struct {
	CombineFS *CombineEmbedFS
	Template  *template.Template
	Delims    render.Delims
	FuncMap   template.FuncMap
}

func NewCombineTemplates

func NewCombineTemplates(combineFS *CombineEmbedFS) *CombineTemplates

func (*CombineTemplates) Instance

func (c *CombineTemplates) Instance(name string, ctx any) render.Render

gin.render.Render

func (*CombineTemplates) RenderError

func (c *CombineTemplates) RenderError(name, source string, data any, err error) render.Render

type Config

type Config struct {
	ID       uint   `json:"id" gorm:"primaryKey"`
	Key      string `json:"key" gorm:"size:128;uniqueIndex"`
	Desc     string `json:"desc" gorm:"size:200"`
	Autoload bool   `json:"autoload" gorm:"index"`
	Public   bool   `json:"public" gorm:"index" default:"false"`
	Format   string `json:"format" gorm:"size:20" default:"text" comment:"json,yaml,int,float,bool,text"`
	Value    string
}

func LoadPublicConfigs

func LoadPublicConfigs(db *gorm.DB) []Config

type DebugTempalte

type DebugTempalte struct {
	Template *template.Template
	Name     string
	Data     any
	// contains filtered or unexported fields
}

HTML contains template reference and its name with given interface object.

func (DebugTempalte) Render

func (r DebugTempalte) Render(w http.ResponseWriter) error

Render (HTML) executes template and writes its result with custom ContentType for response.

func (DebugTempalte) WriteContentType

func (r DebugTempalte) WriteContentType(w http.ResponseWriter)

WriteContentType (HTML) writes HTML ContentType.

type EmbedFS

type EmbedFS struct {
	EmbedRoot string
	Embedfs   embed.FS
}

type EmbedFile

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

func (EmbedFile) Close

func (ef EmbedFile) Close() error

Close implements http.File

func (EmbedFile) Read

func (ef EmbedFile) Read(p []byte) (n int, err error)

Read implements http.File

func (EmbedFile) Readdir

func (ef EmbedFile) Readdir(count int) ([]fs.FileInfo, error)

Readdir implements http.File

func (EmbedFile) Seek

func (ef EmbedFile) Seek(offset int64, whence int) (int64, error)

Seek implements http.File

func (EmbedFile) Stat

func (ef EmbedFile) Stat() (fs.FileInfo, error)

Stat implements http.File

type ErrorWithCode

type ErrorWithCode interface {
	StatusCode() int
}

type ExpiredLRUCache

type ExpiredLRUCache[K comparable, V any] struct {
	*lru.Cache[K, expiredLRUCacheValue[V]]
	// contains filtered or unexported fields
}

func NewExpiredLRUCache

func NewExpiredLRUCache[K comparable, V any](size int, expired time.Duration) *ExpiredLRUCache[K, V]

func (*ExpiredLRUCache[K, V]) Add

func (c *ExpiredLRUCache[K, V]) Add(key K, value V) (evicted bool)

func (*ExpiredLRUCache[K, V]) Contains

func (c *ExpiredLRUCache[K, V]) Contains(key K) bool

func (*ExpiredLRUCache[K, V]) Get

func (c *ExpiredLRUCache[K, V]) Get(key K) (value V, ok bool)

func (*ExpiredLRUCache[K, V]) Remove

func (c *ExpiredLRUCache[K, V]) Remove(key K) (present bool)

type Filter

type Filter struct {
	Name  string `json:"name"`
	Op    string `json:"op"`
	Value any    `json:"value"`
	// contains filtered or unexported fields
}

func (*Filter) GetQuery

func (f *Filter) GetQuery() string

GetQuery return the combined filter SQL statement. such as "age >= ?", "name IN ?".

type GetDB

type GetDB func(c *gin.Context, isCreate bool) *gorm.DB // designed for group

type Group

type Group struct {
	ID         uint            `json:"-" gorm:"primaryKey"`
	CreatedAt  time.Time       `json:"-" gorm:"autoCreateTime"`
	UpdatedAt  time.Time       `json:"-"`
	Name       string          `json:"name" gorm:"size:200"`
	Type       string          `json:"type" gorm:"size:64;index"`
	Extra      []GroupExtra    `gorm:"polymorphic:Object;polymorphicValue:group"`
	Permission GroupPermission `json:"-"`
}

func CreateGroupByUser

func CreateGroupByUser(db *gorm.DB, user *User, name string) (*Group, error)

func CurrentGroup

func CurrentGroup(c *gin.Context) *Group

func GetFirstGroupByUser

func GetFirstGroupByUser(db *gorm.DB, user *User) (*Group, error)

func GetGroupByID

func GetGroupByID(db *gorm.DB, groupID uint) (*Group, error)

func GetGroupsByUser

func GetGroupsByUser(db *gorm.DB, user *User) ([]Group, error)

func (Group) String

func (g Group) String() string

type GroupExtra

type GroupExtra struct {
	ID         uint   `json:"-" gorm:"primaryKey"`
	ObjectType string `json:"type"  gorm:"size:128;uniqueIndex:idx_group_extra_object_id_key"`
	ObjectID   uint   `json:"-" gorm:"uniqueIndex:idx_group_extra_object_id_key"`
	Key        string `json:"key" gorm:"size:128;uniqueIndex:idx_group_extra_object_id_key"`
	Value      string `json:"value"`
}

type GroupMember

type GroupMember struct {
	ID          uint         `json:"-" gorm:"primaryKey"`
	CreatedAt   time.Time    `json:"-" gorm:"autoCreateTime"`
	JoinedAt    *time.Time   `json:"joinedAt,omitempty"`
	UserID      uint         `json:"-"`
	User        User         `json:"user"`
	GroupID     uint         `json:"-"`
	Group       Group        `json:"group"`
	Role        string       `json:"role" gorm:"size:100"`
	Description string       `json:"description,omitempty"`
	Extra       []GroupExtra `gorm:"polymorphic:Object;polymorphicValue:member"`
}

type GroupPermission

type GroupPermission struct {
	Permissions []string
}

permission format users.read,users.create,users.update,users.delete, user.* pages.publish,pages.update,page.delete,page.*

func (*GroupPermission) Scan

func (p *GroupPermission) Scan(value interface{}) error

func (GroupPermission) Value

func (p GroupPermission) Value() (driver.Value, error)

type LoginForm

type LoginForm struct {
	Email     string `json:"email" comment:"Email address"`
	Password  string `json:"password,omitempty"`
	Timezone  string `json:"timezone,omitempty"`
	Remember  bool   `json:"remember,omitempty"`
	AuthToken string `json:"token,omitempty"`
}

type Order

type Order struct {
	Name string `json:"name"`
	Op   string `json:"op"`
}

func (*Order) GetQuery

func (f *Order) GetQuery() string

GetQuery return the combined order SQL statement. such as "id DESC".

type PrepareQuery

type PrepareQuery func(db *gorm.DB, c *gin.Context) (*gorm.DB, *QueryForm, error)

type Profile

type Profile struct {
	Avatar       string         `json:"avatar,omitempty"`
	Gender       string         `json:"gender,omitempty"`
	City         string         `json:"city,omitempty"`
	Region       string         `json:"region,omitempty"`
	Country      string         `json:"country,omitempty"`
	Extra        map[string]any `json:"extra,omitempty"`
	PrivateExtra map[string]any `json:"privateExtra,omitempty"`
}

func (*Profile) Scan

func (p *Profile) Scan(value interface{}) error

func (Profile) Value

func (p Profile) Value() (driver.Value, error)

type QueryForm

type QueryForm struct {
	Pos         int      `json:"pos"`
	Limit       int      `json:"limit"`
	Keyword     string   `json:"keyword,omitempty"`
	Filters     []Filter `json:"filters,omitempty"`
	Orders      []Order  `json:"orders,omitempty"`
	ForeignMode bool     `json:"foreign"` // for foreign key
	ViewFields  []string `json:"-"`       // for view
	// contains filtered or unexported fields
}

func DefaultPrepareQuery

func DefaultPrepareQuery(db *gorm.DB, c *gin.Context) (*gorm.DB, *QueryForm, error)

DefaultPrepareQuery return default QueryForm.

type QueryResult

type QueryResult struct {
	TotalCount int    `json:"total,omitempty"`
	Pos        int    `json:"pos,omitempty"`
	Limit      int    `json:"limit,omitempty"`
	Keyword    string `json:"keyword,omitempty"`
	Items      []any  `json:"items"`
}

type QueryView

type QueryView struct {
	Path    string `json:"path"`
	Method  string `json:"method"`
	Desc    string `json:"desc"`
	Prepare PrepareQuery
}

type RegisterUserForm

type RegisterUserForm struct {
	Email       string `json:"email" binding:"required"`
	Password    string `json:"password" binding:"required"`
	DisplayName string `json:"displayName"`
	FirstName   string `json:"firstName"`
	LastName    string `json:"lastName"`
	Locale      string `json:"locale"`
	Timezone    string `json:"timezone"`
	Source      string `json:"source"`
}

type ResetPasswordDoneForm

type ResetPasswordDoneForm struct {
	Password string `json:"password" form:"password" binding:"required"`
	Email    string `json:"email" form:"email" binding:"required"`
	Token    string `json:"token" form:"token" binding:"required"`
}

type ResetPasswordForm

type ResetPasswordForm struct {
	Email string `json:"email" binding:"required"`
}

type SigHandler

type SigHandler struct {
	ID      uint
	Handler SignalHandler
}

type SigHandlerEvent

type SigHandlerEvent struct {
	EvType     int
	SignalName string
	SigHandler SigHandler
}

type SignalHandler

type SignalHandler func(sender any, params ...any)

type Signals

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

func NewSignals

func NewSignals() *Signals

func Sig

func Sig() *Signals

func (*Signals) Clear

func (s *Signals) Clear(events ...string)

func (*Signals) Connect

func (s *Signals) Connect(event string, handler SignalHandler) uint

func (*Signals) Disconnect

func (s *Signals) Disconnect(event string, id uint)

func (*Signals) Emit

func (s *Signals) Emit(event string, sender any, params ...any)

type TestClient

type TestClient struct {
	CookieJar http.CookieJar
	Scheme    string
	Host      string
	// contains filtered or unexported fields
}

func NewTestClient

func NewTestClient(r http.Handler) (c *TestClient)

func (*TestClient) Call

func (c *TestClient) Call(method, path string, form any, result any) (err error)

func (*TestClient) CallDelete

func (c *TestClient) CallDelete(path string, form, result any) error

func (*TestClient) CallGet

func (c *TestClient) CallGet(path string, form, result any) error

func (*TestClient) CallPatch

func (c *TestClient) CallPatch(path string, form, result any) error

func (*TestClient) CallPost

func (c *TestClient) CallPost(path string, form any, result any) error

func (*TestClient) CallPut

func (c *TestClient) CallPut(path string, form, result any) error

func (*TestClient) Get

Get return *httptest.ResponseRecoder

func (*TestClient) Post

func (c *TestClient) Post(method, path string, body []byte) *httptest.ResponseRecorder

Post return *httptest.ResponseRecoder

func (*TestClient) SendReq

func (c *TestClient) SendReq(path string, req *http.Request) *httptest.ResponseRecorder

type User

type User struct {
	ID        uint      `json:"-" gorm:"primaryKey"`
	CreatedAt time.Time `json:"-" gorm:"autoCreateTime"`
	UpdatedAt time.Time `json:"-" gorm:"autoUpdateTime"`

	Email       string     `json:"email" gorm:"size:128;uniqueIndex"`
	Password    string     `json:"-" gorm:"size:128"`
	Phone       string     `json:"phone,omitempty" gorm:"size:64;index"`
	FirstName   string     `json:"firstName,omitempty" gorm:"size:128"`
	LastName    string     `json:"lastName,omitempty" gorm:"size:128"`
	DisplayName string     `json:"displayName,omitempty" gorm:"size:128"`
	IsSuperUser bool       `json:"-"`
	IsStaff     bool       `json:"isStaff,omitempty"`
	Enabled     bool       `json:"-"`
	Activated   bool       `json:"-"`
	LastLogin   *time.Time `json:"lastLogin,omitempty"`
	LastLoginIP string     `json:"-" gorm:"size:128"`

	Source    string   `json:"-" gorm:"size:64;index"`
	Locale    string   `json:"locale,omitempty" gorm:"size:20"`
	Timezone  string   `json:"timezone,omitempty" gorm:"size:200"`
	Profile   *Profile `json:"profile,omitempty"`
	AuthToken string   `json:"token,omitempty" gorm:"-"`
}

func CreateUser

func CreateUser(db *gorm.DB, email, password string) (*User, error)

func CurrentUser

func CurrentUser(c *gin.Context) *User

func DecodeHashToken

func DecodeHashToken(db *gorm.DB, hash string, useLastLogin bool) (user *User, err error)

func GetUserByEmail

func GetUserByEmail(db *gorm.DB, email string) (user *User, err error)

func GetUserByUID

func GetUserByUID(db *gorm.DB, userID uint) (*User, error)

func (*User) GetProfile

func (u *User) GetProfile() Profile

func (*User) GetVisibleName

func (u *User) GetVisibleName() string

func (User) String

func (u User) String() string

type WebObject

type WebObject struct {
	Model             any
	Group             string
	Name              string
	Desc              string
	AuthRequired      bool
	Editables         []string
	Filterables       []string
	Orderables        []string
	Searchables       []string
	GetDB             GetDB
	PrepareQuery      PrepareQuery
	BeforeCreate      BeforeCreateFunc
	BeforeUpdate      BeforeUpdateFunc
	BeforeDelete      BeforeDeleteFunc
	BeforeRender      BeforeRenderFunc
	BeforeQueryRender BeforeQueryRenderFunc

	Views        []QueryView
	AllowMethods int
	// contains filtered or unexported fields
}

func (*WebObject) Build

func (obj *WebObject) Build() error

Build fill the properties of obj.

func (*WebObject) BuildPrimaryPath

func (obj *WebObject) BuildPrimaryPath(prefix string) string

func (*WebObject) RegisterObject

func (obj *WebObject) RegisterObject(r *gin.RouterGroup) error

type WebObjectPrimaryField

type WebObjectPrimaryField struct {
	IsPrimary bool
	Name      string
	Kind      reflect.Kind
	JSONName  string
}

type Worker

type Worker[T any] struct {
	Name      string
	Num       int
	QueueSize int
	Handler   func(T) error
	DumpStats func(queueSize, doneCount int, avgUsage time.Duration)
	// contains filtered or unexported fields
}

func (*Worker[T]) Push

func (w *Worker[T]) Push(req T) error

func (*Worker[T]) Start

func (w *Worker[T]) Start(ctx context.Context)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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