gweb

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2025 License: MIT Imports: 41 Imported by: 0

README

gweb

介绍

基于Gin和Gorm的web框架

软件架构

软件架构说明

安装教程
  1. xxxx
  2. xxxx
  3. xxxx
使用说明
  1. xxxx
  2. xxxx
  3. xxxx
参与贡献
  1. Fork 本仓库
  2. 新建 Feat_xxx 分支
  3. 提交代码
  4. 新建 Pull Request
特技
  1. 使用 Readme_XXX.md 来支持不同的语言,例如 Readme_en.md, Readme_zh.md
  2. Gitee 官方博客 blog.gitee.com
  3. 你可以 https://gitee.com/explore 这个地址来了解 Gitee 上的优秀开源项目
  4. GVP 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
  5. Gitee 官方提供的使用手册 https://gitee.com/help
  6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 https://gitee.com/gitee-stars/

Documentation

Index

Constants

View Source
const (
	JoinTypeDB  = 1
	JoinTypeStr = 2
)

Variables

This section is empty.

Functions

func BcryptCheck

func BcryptCheck(password, hash string) bool

BcryptCheck 对比明文密码和数据库的哈希值

func BcryptHash

func BcryptHash(password string) string

BcryptHash 使用 bcrypt 对密码进行加密

func CloneDB

func CloneDB(db *gorm.DB) *gorm.DB

func UseAppState

func UseAppState(router *RouterGroup)

Types

type AppHandler

type AppHandler interface {
	// RegisterModels(app *GinApp)
	// RegisterRoutes(app *GinApp)
	BeforeRun(app *GinApp)
	OnError(app *GinApp, err error, traceback string)
	OnRouteVersionChanged(app *Context, routeVersion string, reqVersion string)
}

type AppState

type AppState string
const (
	StateRunning  AppState = "running"  // 运行中
	StateMaintain AppState = "maintain" // 维护状态
)

type AppStateView

type AppStateView struct{}

func (*AppStateView) AddRoutes

func (view *AppStateView) AddRoutes(router *RouterGroup)

func (*AppStateView) GetState

func (view *AppStateView) GetState(c *Context)

func (*AppStateView) SetState

func (view *AppStateView) SetState(c *Context)

func (*AppStateView) StartMaintain

func (view *AppStateView) StartMaintain(c *Context)

func (*AppStateView) StopMaintain

func (view *AppStateView) StopMaintain(c *Context)

type Claim

type Claim struct {
	jwt.RegisteredClaims
	IsSuperuser bool
	UserClaim   any
}

func (*Claim) Bind

func (c *Claim) Bind(dest any) error

type Context

type Context struct {
	*gin.Context
	App   *GinApp
	Route *Route
	// contains filtered or unexported fields
}

func NewContext

func NewContext(app *GinApp, ctx *gin.Context) *Context

func (*Context) BindUserClaim

func (c *Context) BindUserClaim(dest any) error

func (*Context) Error

func (c *Context) Error(err string)

func (*Context) Errorf

func (c *Context) Errorf(err string, args ...any)

func (*Context) Fail

func (c *Context) Fail(message string)

func (*Context) FailWithData

func (c *Context) FailWithData(message string, data any)

func (*Context) Failf

func (c *Context) Failf(message string, args ...any)

func (*Context) File

func (c *Context) File(filepath string, deleteAfterRespond bool)

func (*Context) FileAttachment

func (c *Context) FileAttachment(filepath string, filename string, deleteAfterRespond bool)

func (*Context) GetClaim

func (c *Context) GetClaim() *Claim

func (*Context) GetData

func (c *Context) GetData(key string, defaultVal any) any

func (*Context) GetRawData

func (c *Context) GetRawData() ([]byte, error)

读取Body数据

func (*Context) MustGetClaim

func (c *Context) MustGetClaim() *Claim

func (*Context) ParamFloat32

func (c *Context) ParamFloat32(key string, defaultValue float32) float32

func (*Context) ParamFloat64

func (c *Context) ParamFloat64(key string, defaultValue float64) float64

func (*Context) ParamInt

func (c *Context) ParamInt(key string, defaultValue int) int

func (*Context) QueryInt

func (c *Context) QueryInt(key string, defaultValue int64) int64

func (*Context) RawMap

func (c *Context) RawMap() map[string]any

func (*Context) ShouldBind

func (c *Context) ShouldBind(obj any) map[string]any

根据请求方式处理数据绑定,一般用于GET和POST都支持的查询接口

func (*Context) ShouldBindForm

func (c *Context) ShouldBindForm(key string, dest any)

func (*Context) ShouldBindJSON

func (c *Context) ShouldBindJSON(obj any) map[string]any

替代ShouldBindJSON,同时返回经过过滤的map数据

func (*Context) ShouldBindQuery

func (c *Context) ShouldBindQuery(obj interface{})

func (*Context) Success

func (c *Context) Success()

func (*Context) SuccessWithData

func (c *Context) SuccessWithData(data any)

type CronTaskInfo

type CronTaskInfo struct {
	CronID         cron.EntryID `json:"cron_id"`
	Key            string       `json:"key"`
	Name           string       `json:"name"`
	CronExpression string       `json:"cron_expression"`
	Desc           string       `json:"desc"`
	Enabled        bool         `json:"enabled"`
	AllowPause     bool         `json:"allow_pause"`
	AllowStop      bool         `json:"allow_stop,omitempty"`
	State          TaskState    `json:"state"`
	TimeStart      *time.Time   `json:"time_start,omitempty"`
	TimeEnd        *time.Time   `json:"time_end,omitempty"`
	TimeCost       float64      `json:"time_cost,omitempty"` // 运行耗时
	Error          string       `json:"error,omitempty"`
	Traceback      string       `json:"traceback,omitempty"`
}

func (*CronTaskInfo) IsIdle

func (info *CronTaskInfo) IsIdle() bool

type DB

type DB struct {
	*gorm.DB

	PanicIfError bool
	// contains filtered or unexported fields
}

func Connect

func Connect(config conf.DbConfig) *DB

Connect 连接数据库

func (*DB) Clone

func (db *DB) Clone() *DB

克隆对象

func (*DB) Count

func (db *DB) Count() (int64, error)

Count计数

func (*DB) Create

func (db *DB) Create(value ...any) error

Create inserts value

func (*DB) CreateInBatches

func (db *DB) CreateInBatches(value any, batchSize int) error

func (*DB) Delete

func (db *DB) Delete(value interface{}, conds ...interface{}) error

func (*DB) Distinct

func (db *DB) Distinct(args ...interface{}) *DB

func (*DB) Exec

func (db *DB) Exec(sql string, value ...any) error

执行SQL

func (*DB) Find

func (db *DB) Find(dest any, conds ...any) error

func (*DB) FindOrPaginate

func (db *DB) FindOrPaginate(dest any, pi int, ps int) (any, error)

根据需要选择分页或者不分页,用于接口中分页或者不分页都要支持的情况

func (*DB) First

func (db *DB) First(dest any, conds ...any) error

func (*DB) FirstAndInit

func (db *DB) FirstAndInit(dest any, attrs ...any) error

func (*DB) FirstOrCreate

func (db *DB) FirstOrCreate(dest any, attrs ...any) error

func (*DB) FirstOrInit

func (db *DB) FirstOrInit(dest any, attrs ...any) error

func (*DB) Group

func (db *DB) Group(fields ...string) *DB

group by 分组查询,在原有的基础上,允许将group字段分散在不同的地方

func (*DB) Joins

func (db *DB) Joins(query string, args ...interface{}) *DB

加强版的Joins,支持Select字段追加,比如:

db.Joins("Project", DB.Select("id", "name"))

db.Joins("Project", DB.Select("fullname"))

相当于:db.Joins("Project", DB.Select("id", "name", "fullname"))

不至于使后写的冲掉前面的,有些逻辑场景下,查询但不需要Select字段,有些则需要, 但两个逻辑同时出现在一个复杂逻辑中, 就不允许相互冲掉

func (*DB) Last

func (db *DB) Last(dest any, conds ...any) error

func (*DB) Limit

func (db *DB) Limit(limit int) *DB

func (*DB) Model

func (db *DB) Model(value any) *DB

func (*DB) NewGroup

func (db *DB) NewGroup(fields ...string) *DB

放弃之前的group,开始组织新的group语句

func (*DB) NewSelect

func (db *DB) NewSelect(query interface{}, args ...interface{}) *DB

不继承之前的Select字段,重新开始

func (*DB) Offset

func (db *DB) Offset(offset int) *DB

func (*DB) Omit

func (db *DB) Omit(columns ...string) *DB

增改查时要忽略的字段

func (*DB) Or

func (db *DB) Or(query interface{}, args ...interface{}) *DB

func (*DB) Order

func (db *DB) Order(fields ...string) *DB

func (*DB) Paginate

func (db *DB) Paginate(dest any, pi int, ps int) (*Pagination[any], error)

func (*DB) PaginateScan

func (db *DB) PaginateScan(dest any, pi int, ps int) (*Pagination[any], error)

func (*DB) Panic

func (db *DB) Panic() *DB

遇到 error 直接 panic,不是底层开发就没必要不厌其烦得判断 error 返回,除了增加代码量,没啥意义

func (*DB) Preload

func (db *DB) Preload(query string, args ...interface{}) *DB

func (*DB) Raw

func (db *DB) Raw(sql string, values ...interface{}) *DB

func (*DB) RowsAffected

func (db *DB) RowsAffected() int64

获取影响的记录数

func (*DB) Run

func (db *DB) Run(fc func(db *DB)) *DB

封装执行逻辑块,方便变量起名困难症患者

func (*DB) Save

func (db *DB) Save(value any, omitFK bool) error

在原版的基础上支持直接忽略外键字段,而不需要明确调用Omit来忽略某个字段

func (*DB) Scan

func (db *DB) Scan(dest any) error

注意SUM不要直接Scan,避免意料之外的异常

func (*DB) ScanOrPaginate

func (db *DB) ScanOrPaginate(dest any, pi int, ps int) (any, error)

func (*DB) Select

func (db *DB) Select(query interface{}, args ...interface{}) *DB

Select 查询字段,在原版的基础上支持散落于不同逻辑,这在复杂的逻辑场景下有用,比如动态统计API的字段不是固定的

func (*DB) Sum

func (db *DB) Sum(query string) (float64, error)

func (*DB) Table

func (db *DB) Table(name string) *DB

func (*DB) Transaction

func (db *DB) Transaction(fc func(tx *DB) error) error

事务

func (*DB) Update

func (db *DB) Update(column string, value interface{}) error

func (*DB) UpdateOrCreate

func (db *DB) UpdateOrCreate(dest any, conds map[string]any, data map[string]any) error

func (*DB) Updates

func (db *DB) Updates(data any) error

func (*DB) Where

func (db *DB) Where(query any, args ...any) *DB

WHERE 查询,在原版的基础上支持 map,比如:

db.Where(map[string]any{
    "age": 20
})

db.Where(map[string]any{
    "age > ?": 20,
})

注意 "age > ?" 不能去掉空格写成 "age>?"

有些情况下,updates的map也需要作为判断条件查询数据,此时可以直接用,nil 会处理为 IS NULL

type EventHandler

type EventHandler func()

type GinApp

type GinApp struct {
	*gin.Engine

	Directory string
	DB        *DB
	Models    []any
	JWT       *JWT
	Tasks     *TaskManager
	Viper     *viper.Viper
	// contains filtered or unexported fields
}

func Application

func Application(opts ...gin.OptionFunc) *GinApp

func (*GinApp) BeforeRun

func (app *GinApp) BeforeRun(f EventHandler)

func (*GinApp) BindConfig

func (app *GinApp) BindConfig(key string, dest any) error

绑定自定义配置

func (*GinApp) GetConfig

func (app *GinApp) GetConfig() *conf.AppConfig

获取配置

func (*GinApp) Group

func (app *GinApp) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup

func (*GinApp) InitEnv

func (app *GinApp) InitEnv(env string) error

func (*GinApp) LogDirectory

func (app *GinApp) LogDirectory() string

func (*GinApp) MigrateDbModels

func (app *GinApp) MigrateDbModels()

迁移数据模型

func (*GinApp) OnError

func (app *GinApp) OnError(f EventHandler)

func (*GinApp) RegisterCommand

func (app *GinApp) RegisterCommand(command *cobra.Command)

注册命令

func (*GinApp) RegisterModels

func (app *GinApp) RegisterModels(models ...any)

注册数据模型

func (*GinApp) RegisterVariable

func (app *GinApp) RegisterVariable(v Variable)

func (*GinApp) Run

func (app *GinApp) Run(addr string)

func (*GinApp) RunCommand

func (app *GinApp) RunCommand(f func(cmdargs map[string]any))

func (*GinApp) RunFromCommand

func (app *GinApp) RunFromCommand()

从命令行执行

func (*GinApp) SetResource

func (app *GinApp) SetResource(resource embed.FS)

func (*GinApp) SetState

func (app *GinApp) SetState(state AppState)

func (*GinApp) StaticDirectory

func (app *GinApp) StaticDirectory() string

func (*GinApp) UseHandler

func (app *GinApp) UseHandler(handler AppHandler)

type GormColumn

type GormColumn struct {
	IsPrimaryKey bool   `json:"primary_key" form:"primary_key"`
	Column       string `json:"column" form:"column"`         // 数据库字段名称
	FieldName    string `json:"field_name" form:"field_name"` // 字段名称
	FieldType    string `json:"field_type" form:"field_type"`
	Size         int    `json:"size" form:"size"`
	IsFKField    bool   `json:"is_fk_field"`
	DefaultValue string `json:"default_value" form:"default_value"`
}

func AnalyzeGormTags

func AnalyzeGormTags(f reflect.StructField) *GormColumn

分析GORM标签的函数

type HandlerFunc

type HandlerFunc func(*Context)

func AllowIfMaintain

func AllowIfMaintain() HandlerFunc

系统维护时放行

func MiddlewareJWT

func MiddlewareJWT(config *conf.AppConfig) HandlerFunc

func MustBeSuperuser

func MustBeSuperuser() HandlerFunc

必须是超级管理员

type HttpMethod

type HttpMethod string
const (
	HttpGET     HttpMethod = "GET"
	HttpPOST    HttpMethod = "POST"
	HttpPUT     HttpMethod = "PUT"
	HttpDELETE  HttpMethod = "DELETE"
	HttpPATCH   HttpMethod = "PATCH"
	HttpOPTIONS HttpMethod = "OPTIONS"
	HttpHEAD    HttpMethod = "HEAD"
)

type IAppTask

type IAppTask interface {
	GetInfo() *CronTaskInfo
	UpdateInfo(info CronTaskInfo)
	Run(handler *TaskHandler) error
}

type IRouteView

type IRouteView interface {
	AddRoutes(router *RouterGroup)
}

路由视图接口

type JWT

type JWT struct {
	*conf.JwtConfig
}

func (*JWT) MakeToken

func (j *JWT) MakeToken(payload any, isSuperuser bool) (string, error)

func (*JWT) ParseToken

func (j *JWT) ParseToken(token string) (*Claim, error)

type LogView

type LogView struct{}

func (*LogView) RegisterRoutes

func (view *LogView) RegisterRoutes(router *RouterGroup)

type Model

type Model struct {
	ID        uint       `gorm:"primarykey" json:"id"`
	CreatedAt *time.Time `gorm:"not null;default:CURRENT_TIMESTAMP(3);comment:创建时间" json:"created_at,omitempty"`
	UpdatedAt *time.Time `gorm:"default:NULL on update CURRENT_TIMESTAMP(3);comment:更新时间" json:"updated_at,omitempty"`
	DeletedAt *time.Time `gorm:"index" json:"deleted_at,omitempty"`
}

基础模型

type Pagination

type Pagination[T any] struct {
	PageIndex int   `json:"pi"`
	PageSize  int   `json:"ps"`
	List      T     `json:"list"`
	Total     int64 `json:"total"`
}

type QuerySet

type QuerySet[T any] struct {
	*DB
}

DB的泛型版本

func Q

func Q[T any](db *DB) *QuerySet[T]

func (*QuerySet[T]) Clone

func (qs *QuerySet[T]) Clone() *QuerySet[T]

func (*QuerySet[T]) Conds

func (qs *QuerySet[T]) Conds(conds map[string]any) *QuerySet[T]

func (*QuerySet[T]) Distinct

func (qs *QuerySet[T]) Distinct(args ...interface{}) *QuerySet[T]

func (*QuerySet[T]) FindAll

func (qs *QuerySet[T]) FindAll() ([]T, error)

func (*QuerySet[T]) FindOrPaginate2

func (qs *QuerySet[T]) FindOrPaginate2(pi int, ps int) (any, error)

func (*QuerySet[T]) ForEach

func (qs *QuerySet[T]) ForEach(callback func(record T) error) error

func (*QuerySet[T]) GetFirst

func (qs *QuerySet[T]) GetFirst(conds ...any) (*T, error)

func (*QuerySet[T]) Group

func (qs *QuerySet[T]) Group(fields ...string) *QuerySet[T]

group by 分组查询,在原有的基础上,允许将group字段分散在不同的地方

func (*QuerySet[T]) Joins

func (qs *QuerySet[T]) Joins(query string, args ...interface{}) *QuerySet[T]

func (*QuerySet[T]) Limit

func (qs *QuerySet[T]) Limit(limit int) *QuerySet[T]

func (*QuerySet[T]) Offset

func (qs *QuerySet[T]) Offset(offset int) *QuerySet[T]

func (*QuerySet[T]) Omit

func (qs *QuerySet[T]) Omit(columns ...string) *QuerySet[T]

func (*QuerySet[T]) Or

func (qs *QuerySet[T]) Or(query interface{}, args ...interface{}) *QuerySet[T]

func (*QuerySet[T]) Order

func (qs *QuerySet[T]) Order(fields ...string) *QuerySet[T]

func (*QuerySet[T]) Paginate2

func (qs *QuerySet[T]) Paginate2(pi int, ps int) (*Pagination[[]T], error)

func (*QuerySet[T]) Panic

func (qs *QuerySet[T]) Panic() *QuerySet[T]

func (*QuerySet[T]) Preload

func (qs *QuerySet[T]) Preload(query string, args ...interface{}) *QuerySet[T]

func (*QuerySet[T]) Raw

func (qs *QuerySet[T]) Raw(sql string, values ...interface{}) *QuerySet[T]

func (*QuerySet[T]) Run

func (qs *QuerySet[T]) Run(fc func(qs *QuerySet[T])) *QuerySet[T]

func (*QuerySet[T]) Select

func (qs *QuerySet[T]) Select(query interface{}, args ...interface{}) *QuerySet[T]

func (*QuerySet[T]) Table

func (qs *QuerySet[T]) Table(name string) *QuerySet[T]

func (*QuerySet[T]) Where

func (qs *QuerySet[T]) Where(query any, args ...any) *QuerySet[T]

type Route

type Route struct {
	App          *GinApp
	RelativePath string
	// contains filtered or unexported fields
}

func (*Route) AddInfo

func (r *Route) AddInfo(info gx.M) *Route

func (*Route) GetInfo

func (r *Route) GetInfo(key string) any

func (*Route) IsMaintainAllow

func (r *Route) IsMaintainAllow() bool

func (*Route) MaintainAllow

func (r *Route) MaintainAllow()

func (*Route) SetInfo

func (r *Route) SetInfo(key string, value any) *Route

type RouterGroup

type RouterGroup struct {
	*gin.RouterGroup
	RelativePath string

	App *GinApp
}

func (*RouterGroup) AddViews

func (r *RouterGroup) AddViews(views ...IRouteView)

func (*RouterGroup) Config

func (r *RouterGroup) Config(relativePath string, fc func(*RouterGroup)) *RouterGroup

func (*RouterGroup) DELETE

func (r *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) *Route

func (*RouterGroup) GET

func (r *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) *Route

func (*RouterGroup) Group

func (r *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup

func (*RouterGroup) HEAD

func (r *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) *Route

func (*RouterGroup) OPTIONS

func (r *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) *Route

func (*RouterGroup) PATCH

func (r *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) *Route

func (*RouterGroup) POST

func (r *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) *Route

func (*RouterGroup) PUT

func (r *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) *Route

func (*RouterGroup) UseMiddleware

func (r *RouterGroup) UseMiddleware(middleware ...HandlerFunc) *RouterGroup

type TaskHandler

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

func NewTaskHandler

func NewTaskHandler() *TaskHandler

func (*TaskHandler) OnPause

func (t *TaskHandler) OnPause(callback func())

func (*TaskHandler) OnResume

func (t *TaskHandler) OnResume(callback func())

func (*TaskHandler) OnStop

func (t *TaskHandler) OnStop(callback func())

func (*TaskHandler) Pause

func (t *TaskHandler) Pause()

暂停

func (*TaskHandler) Resume

func (t *TaskHandler) Resume()

恢复

func (*TaskHandler) Stop

func (t *TaskHandler) Stop()

func (*TaskHandler) Wait

func (t *TaskHandler) Wait()

type TaskManager

type TaskManager struct {
	*cron.Cron
	// contains filtered or unexported fields
}

func NewTaskManager

func NewTaskManager() *TaskManager

func (*TaskManager) AddTask

func (m *TaskManager) AddTask(task IAppTask) (IAppTask, error)

func (*TaskManager) PauseTask

func (m *TaskManager) PauseTask(task IAppTask)

func (*TaskManager) RegisterRoutes

func (m *TaskManager) RegisterRoutes(router *RouterGroup)

func (*TaskManager) ResumeTask

func (m *TaskManager) ResumeTask(task IAppTask)

func (*TaskManager) RunTask

func (m *TaskManager) RunTask(task IAppTask) error

func (*TaskManager) StopTask

func (m *TaskManager) StopTask(task IAppTask) error

func (*TaskManager) UpdateTask

func (m *TaskManager) UpdateTask(task IAppTask)

type TaskState

type TaskState string
const (
	TaskStatePending TaskState = "pending" // 等待执行
	TaskStateRunning TaskState = "running" // 执行中
	TaskStatePaused  TaskState = "paused"  // 暂停
	TaskStateStopped TaskState = "stopped" // 停止
	TaskStateError   TaskState = "error"   // 执行出错
	TaskStateDone    TaskState = "done"    // 已完成
)

type Variable

type Variable struct {
	Name     string       `json:"name"`
	Key      string       `json:"key"`
	Module   string       `json:"module"` // 适用场景
	GetValue VariableFunc `json:"-"`
}

type VariableFunc

type VariableFunc func(c *Context) any

type VariableView

type VariableView struct{}

func (*VariableView) RegisterRoutes

func (view *VariableView) RegisterRoutes(router *RouterGroup)

Directories

Path Synopsis
utils

Jump to

Keyboard shortcuts

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