hwf

package module
v0.0.0-...-ba98abd Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2025 License: MIT Imports: 32 Imported by: 0

README

HWF: 轻量 Go Web 框架

项目介绍

HWF (Hello Web Framework) 是一个轻量级的 Go Web 框架,旨在提供简洁、易用且功能完善的 Web 开发体验。框架遵循模块化设计理念,支持项目与模块生命周期管理、INI 配置、路由绑定与校验、定时任务、钩子机制、统一上下文、日志按天滚动等核心功能。

核心思想
  • 模块化设计:将应用拆分为多个独立模块,每个模块拥有自己的生命周期、路由、模型和定时任务
  • 自动数据库表创建:基于 GORM 模型自动创建和迁移数据库表,简化数据库操作
  • 统一上下文:提供统一的 Context 对象,方便在请求处理过程中访问日志、ORM 事务等资源
  • 灵活配置:支持 INI 格式配置文件,可通过命令行参数指定配置文件
  • 丰富的中间件支持:提供路由级中间件,支持统一处理请求日志、鉴权等功能

快速使用

安装 CLI 工具
 go install gitee.com/hwfo/hwf/cmd/hwf@latest
创建新项目
hwf new myapp
cd myapp
创建模块
# 在项目根目录下执行
hwf module user
运行项目
# 使用默认配置文件 (config.ini)
go run main.go

# 使用指定配置文件
go run main.go config.prod.ini
最小项目示例
package main

import (
    "github.com/hwf"
)

type MyApp struct{}

func (a *MyApp) Name() string { return "myapp" }
func (a *MyApp) Install(ctx *hwf.HwfCtx) error { return nil }
func (a *MyApp) Init(ctx *hwf.HwfCtx) error { return nil }
func (a *MyApp) Modules() []hwf.Module { return []hwf.Module{} }
func (a *MyApp) Config() any { return nil }

func main() {
    app := &MyApp{}
	err := hwf.Run(app)
	if err != nil {
		log.Fatalln(err.Error())
	}
}

项目结构

HWF 推荐的项目目录结构如下:

├── config.ini              # 主配置文件
├── main.go                 # 应用入口
├── internal/               # 模块代码根目录
│   └── <module1>/           # 模块目录
│   └── <module2>/           # 模块目录
├── resource/               # 嵌入式资源目录 (go:embed)
├── static/                 # 静态资源目录
├── runtime/                # 运行时目录
├── logs/                   # 日志目录
├── manifest/               # 部署相关文件
├── pkg/                    # 项目内通用工具包
└── go.mod                  # Go 模块文件
应用接口实现

应用需要实现 hwf.App 接口:

type App interface {
    // Name 返回项目名称
    Name() string
    // Install 首次运行时执行 (当 runtime/install.lock 不存在时)
    Install(ctx *HwfCtx) error
    // Init 每次运行时执行
    Init(ctx *HwfCtx) error
    // Route 注册路由
    Route(r Router)
    // Modules 返回需要注册的模块列表
    Modules() []Module
    // Config 返回项目配置结构体指针,可读取ini配置文件中[app]部分的配置
    Config() any
}
可选接口
  • AppTLSConfiger: 提供 TLS 配置
  • AppJSONFormatter: 自定义 JSON 输出格式
  • AppPackResourcer: 提供嵌入式资源文件系统
  • ConfigFiler: 提供配置文件路径

模块接口

模块是框架的基本功能单元,每个模块需要实现 hwf.Module 接口:

type Module interface {
    // Name 返回模块名称
    Name() string
    // Install 首次运行时执行
    Install(ctx *HwfCtx) error
    // Init 每次运行时执行
    Init(ctx *HwfCtx) error
    // Models 返回 GORM 模型结构体,用于自动创建数据库表
    Models() []any
    // Route 注册模块路由
    Route(r Router)
    // Cron 注册定时任务
    Cron(c CronJob)
    // Triggers 声明模块可能触发的钩子名称
    Triggers(h Hooks)
    // Config 返回模块配置结构体指针,可读取配置文件中[module.模块Name()]部分的配置数据
    Config() any
}
模块目录结构
internal/<module>/
├── init.go              # 模块入口,实现 Module 接口
├── define/              # 常量与配置类型
├── model/               # 持久化模型 (GORM)
├── dto/                 # 领域对象与 DTO
├── api/                 # 接口契约与协定
├── control/             # 路由与控制器
├── service/             # 业务服务
├── cron/                # 定时任务实现
└── pkg/                 # 模块内通用工具

配置文件

HWF 使用 INI 格式的配置文件,支持多节配置和内联注释。

配置文件位置
  • 默认配置文件:config.ini
  • 可通过命令行参数指定:go run main.go custom.ini
  • 可通过 ConfigFiler 接口自定义配置文件路径
核心配置节
[logging]
retention_days = 7          # 日志保留天数
log_level = info            # 日志级别: debug|info|warn|error|off
request_log_enabled = true  # 是否记录请求日志
console_enable = true       # 是否输出日志到控制台

[web]
addr = :8080                # 监听地址
read_timeout = 10           # 读取超时时间 (秒)
write_timeout = 10          # 写入超时时间 (秒)
idle_timeout = 60           # 空闲超时时间 (秒)
static_dir = static         # 静态文件目录
static_prefix = /static     # 静态文件前缀

[paths]
logs_dir = logs             # 日志目录
runtime_dir = runtime       # 运行时目录

[database]
driver = sqlite             # 数据库驱动: sqlite|mysql|postgres
dsn = file:app.db?_pragma=busy_timeout(5000)  # 数据源名称
max_open = 25               # 最大打开连接数
max_idle = 25               # 最大空闲连接数
log_sql = false             # 是否记录 SQL 语句
模块配置

模块配置使用 [module.<模块名>] ,可在Module接口的Config中读取

[module.user]
enable_email_verify = true
password_min_length = 8

路由注册

基本路由
func (m *UserModule) Route(r hwf.Router) {
    // 基本路由
    r.GET("/users", m.ListUsers)
    r.POST("/users", m.CreateUser)
    r.GET("/users/:id", m.GetUser)
    r.PUT("/users/:id", m.UpdateUser)
    r.DELETE("/users/:id", m.DeleteUser)
  
    // 匹配所有 HTTP 方法
    r.Any("/health", m.HealthCheck)
}
路由组
func (m *UserModule) Route(r hwf.Router) {
    // 创建路由组
    api := r.Group("/api/v1")
  
    // 路由组中间件
    api.Use(m.AuthMiddleware)
  
    // 组内路由
    api.GET("/users", m.ListUsers)
    api.POST("/users", m.CreateUser)
}
静态文件
// 在模块路由中注册
func (m *StaticModule) Route(r hwf.Router) {
    r.Static("/static", "static")
    r.File("/favicon.ico", "static/favicon.ico")
}

// 或通过配置文件自动注册 (推荐)
// [web]
// static_dir = static
// static_prefix = /static
Context 使用
func (m *UserModule) GetUser(c *hwf.ReqCtx) {
    // 获取用户 ID
    id := c.Query("id")
  
    // 访问框架上下文
    ctx := c.Context()
  
    // 记录日志
    ctx.Log().Infof("获取用户信息: %s", id)
  
    // 数据库事务
    err := ctx.Transaction(func(tx *hwf.ORM) error {
        // 数据库操作...
        return nil
    })
  
    // 返回 JSON 响应
    c.JSON(200, map[string]interface{}{
        "id":   id,
        "name": "张三",
    })
}

数据绑定

基本绑定
func (m *UserModule) CreateUser(c *hwf.ReqCtx) {
    var user dto.User
  
    // 绑定 JSON 请求体
    if err := c.BindJSON(&user); err != nil {
        c.JSON(400, map[string]string{"error": err.Error()})
        return
    }
  
    // 绑定 URL 查询参数
    // if err := c.BindQuery(&user); err != nil {
    //     c.JSON(400, map[string]string{"error": err.Error()})
    //     return
    // }
  
    // 绑定表单数据
    // if err := c.BindForm(&user); err != nil {
    //     c.JSON(400, map[string]string{"error": err.Error()})
    //     return
    // }
  
    // 绑定请求头
    // if err := c.BindHeader(&user); err != nil {
    //     c.JSON(400, map[string]string{"error": err.Error()})
    //     return
    // }
  
    // 处理业务逻辑...
    c.JSON(200, map[string]string{"message": "用户创建成功"})
}
数据校验
package entity

type User struct {
    Username string `json:"username" validate:"required;min=3;max=20" msg:"required=用户名必填;min=用户名长度不能小于3个字符;max=用户名长度不能大于20个字符"`
    Email    string `json:"email" validate:"required;email" msg:"required=邮箱必填;email=邮箱格式不正确"`
    Password string `json:"password" validate:"required;password=strong" msg:"required=密码必填;password=密码强度不足,需至少10位并包含大小写字母、数字和特殊字符"`
    Age      int    `json:"age" validate:"ge=18;le=100" msg:"ge=必须年满18岁;le=年龄不能超过100岁"`
}
校验规则
规则 描述 示例
required 必填字段 validate:"required"
min 最小长度或值 validate:"min=3"
max 最大长度或值 validate:"max=20"
len 固定长度 validate:"len=11"
email 邮箱格式 validate:"email"
eq 等于 validate:"eq=admin"
gt 大于 validate:"gt=18"
lt 小于 validate:"lt=100"
ge 大于等于 validate:"ge=18"
le 小于等于 validate:"le=100"
password 密码强度 validate:"password=strong"
phone 手机号格式 validate:"phone"
date 日期格式 (YYYY-MM-DD) validate:"date"
datetime 日期时间格式 (YYYY-MM-DD HH:MM:SS) validate:"datetime"
idcard 中国身份证号 validate:"idcard"
regex 正则表达式 validate:"regex=^[a-z0-9_]{3,16}$"
in 在指定范围内 validate:"in=admin,user,guest"
notin 不在指定范围内 validate:"notin=admin"
ipv4 IPv4 地址 validate:"ipv4"
ipv6 IPv6 地址 validate:"ipv6"
自定义错误消息
type User struct {
    Username string `json:"username" validate:"required;min=3" msg:"required=用户名不能为空;min=用户名至少需要3个字符"`
}

钩子

注册钩子
func (m *UserModule)Triggers(h hwf.Hooks) {
    // 注册用户创建后的钩子
    h.On("user.created", func(ctx *hwf.Context, payload any) error {
        user := payload.(*entity.User)
        ctx.Log().Infof("用户创建成功,发送欢迎邮件: %s", user.Email)
        // 发送欢迎邮件逻辑...
        return nil
    })
}
触发钩子
func (m *UserService) CreateUser(user *entity.User) error {
    // 保存用户到数据库
    if err := m.DB.Create(user).Error; err != nil {
        return err
    }
  
    // 触发用户创建钩子
    ctx := hwf.NewContext()
    return hwf.GetHooks().Put("user.created", ctx, user)
}

定时任务

注册定时任务
func (m *UserModule) Cron(c hwf.CronJob) {
    // 每 5 秒执行一次
    c.Add("*/5 * * * * *", func(ctx *hwf.Context) {
        ctx.Log().Println("每 5 秒执行一次的任务")
    })
  
    // 每小时执行一次
    c.Add("0 0 * * * *", func(ctx *hwf.Context) {
        ctx.Log().Println("每小时执行一次的任务")
    })
  
    // 每天凌晨 2 点执行
    c.Add("0 0 2 * * *", func(ctx *hwf.Context) {
        ctx.Log().Println("每天凌晨 2 点执行的任务")
        // 执行数据备份...
    })
}
Cron 表达式格式

HWF 支持 6 段 Cron 表达式(含秒):

秒 分 时 日 月 星期
字段 允许值 允许特殊字符
0-59 *, /, -, ,
0-59 *, /, -, ,
0-23 *, /, -, ,
1-31 *, /, -, ,
1-12 *, /, -, ,
星期 0-6 (0=周日) *, /, -, ,

日志

基本日志
// 在请求处理中
func (m *UserModule) GetUser(c *hwf.ReqCtx) {
    ctx := c.Context()
    ctx.Log().Debugf("调试信息: %s", c.R.URL.Path)
    ctx.Log().Infof("普通信息: %s", c.R.URL.Path)
    ctx.Log().Warnf("警告信息: %s", c.R.URL.Path)
    ctx.Log().Errorf("错误信息: %s", c.R.URL.Path)
}

// 在服务层
func (s *UserService) GetUser(id string) (*entity.User, error) {
    ctx := hwf.NewContext()
    ctx.Log().Infof("查询用户: %s", id)
    // ...
}
请求日志

启用请求日志记录:

[logging]
request_log_enabled = true

请求日志格式:

2023-10-01 12:00:00 [INFO] [GET] /api/v1/users 127.0.0.1 200 15ms
日志配置
[logging]
retention_days = 7         # 日志保留天数
log_level = info           # 日志级别: debug|info|warn|error|off
request_log_enabled = true # 是否记录请求日志
console_enable = true    # 是否输出到控制台

[paths]
logs_dir = logs            # 日志目录
日志文件

日志文件按天生成,格式为 YYYY-MM-DD.log,存储在 logs 目录下(可通过配置修改)。

数据库操作

模型定义
package model

import (
    "github.com/hwf"
    "gorm.io/gorm"
)

type User struct {
    gorm.Model
    Username string `gorm:"unique;size:20" json:"username"`
    Email    string `gorm:"unique;size:100" json:"email"`
    Password string `gorm:"size:100" json:"-"`
}

func (u *User) TableName() string { return "users" }
自动迁移

框架会在首次启动时自动迁移所有模块的模型:

func (m *UserModule) Models() []any {
    return []any{&model.User{}}
}
事务处理
func (s *UserService) CreateOrder(c *hwf.ReqCtx, order *model.Order) error {
    return c.Context().Transaction(func(tx *hwf.ORM) error {
        // 创建订单
        if err := tx.Create(order).Error; err != nil {
            return err
        }
  
        // 更新库存
        if err := tx.Model(&model.Product{}).Where("id = ?", order.ProductID).Update("stock", gorm.Expr("stock - ?", order.Quantity)).Error; err != nil {
            return err
        }
  
        return nil
    })
}

中间件

自定义中间件
func (m *AuthModule) AuthMiddleware(c *hwf.ReqCtx) {
    // 从请求头获取 token
    token := c.R.Header.Get("Authorization")
  
    // 验证 token
    if token == "" || !m.ValidateToken(token) {
        c.AbortWithStatusJSON(401, map[string]string{"error": "未授权"})
        return
    }
  
    // 继续执行后续中间件和处理函数
    c.Next()
}
注册中间件
func (m *AuthModule) Route(r hwf.Router) {
    // 全局中间件
    r.Use(m.LogMiddleware)
  
    // 路由组中间件
    api := r.Group("/api")
    api.Use(m.AuthMiddleware)
  
    // 特定路由中间件
    api.GET("/admin", m.AdminMiddleware, m.AdminHandler)
}

高级特性

JSON 格式统一
// 实现 AppJSONFormatter 接口
func (a *MyApp) JSONFormat(ctx *hwf.ReqCtx, v ...any) {
    var code int
    var data any
    var message string
  
    // 根据参数数量和类型统一格式化
    switch len(v) {
    case 1:
        data = v[0]
        code = 200
        message = "success"
    case 2:
        code = v[0].(int)
        data = v[1]
        message = "success"
    case 3:
        code = v[0].(int)
        data = v[1]
        message = v[2].(string)
    }
  
    // 统一响应格式
    ctx.JSON(code, map[string]any{
        "code":    code,
        "message": message,
        "data":    data,
        "time":    time.Now().Unix(),
    })
}

// 使用统一格式
func (m *UserModule) GetUser(c *hwf.ReqCtx) {
    user := &entity.User{ID: 1, Username: "张三"}
    c.JSONF(200, user, "获取用户成功")
    // 输出: {"code":200,"message":"获取用户成功","data":{"id":1,"username":"张三"},"time":1633046400}
}
反向代理
func (m *ProxyModule) Route(r hwf.Router) {
    // 注册反向代理
    r.Proxy("/api", "http://localhost:9000")
}

// 或在请求处理中动态代理
func (C *DynamicController) ProxyHandler(c *hwf.ReqCtx) {
    // 动态计算目标地址
    target := "http://localhost:9000"
  
    // 反向代理
    err := c.Proxy(target, func(p *httputil.ReverseProxy) {
        // 自定义代理配置
        p.ModifyResponse = func(resp *http.Response) error {
            resp.Header.Set("X-Proxy", "HWF")
            return nil
        }
    })
  
    if err != nil {
        c.AbortWithStatusJSON(500, map[string]string{"error": err.Error()})
    }
}

中间件

HWF 提供了丰富的中间件支持,帮助你快速实现常见功能:

中间件 说明 文档
jwt JWT 认证中间件,支持 HS256 签名、自动续签 查看文档
token Token 会话管理中间件,支持多种存储后端 查看文档
permission 权限控制中间件,支持分组权限管理 查看文档

工具包

HWF 提供了一系列实用工具包,可独立使用:

工具包 说明 文档
hconfig 配置管理,支持 JSON 格式配置文件 查看文档
hcache 文件缓存,支持持久化存储 查看文档
hcaptcha 图形验证码生成与验证 查看文档
hconv 类型转换工具集 查看文档
hcrypt 加密解密工具(AES/RSA) 查看文档
hgenerate 随机数/ID/序列号生成 查看文档
hhash 哈希计算工具(MD5/SHA/HMAC) 查看文档
hhttp HTTP 客户端请求工具 查看文档

贡献

欢迎提交 Issue 和 Pull Request!

许可证

MIT License

Documentation

Index

Constants

View Source
const (
	MethodGet    = "GET"
	MethodPost   = "POST"
	MethodPut    = "PUT"
	MethodDelete = "DELETE"
	MethodAny    = "ANY"
)
View Source
const Version = "v1.0.0"

Variables

This section is empty.

Functions

func CloseAllRedis

func CloseAllRedis()

closeAllRedis closes all Redis connections (called on shutdown).

func CtxGet

func CtxGet[T any](c *HwfCtx, key string) (T, bool)

Returns zero value and false if key is missing or type assertion fails.

func Do

func Do(fn func() error) (e error)

Do 包裹一个函数,捕获 panic 并返回错误。

func GetNamedRedis

func GetNamedRedis(name string) *redis.Client

GetNamedRedis returns a named Redis client by name (e.g., "001", "002"). Returns nil if the named Redis is not configured.

func GetRedis

func GetRedis() *redis.Client

GetRedis returns the default Redis client. Returns nil if Redis is not configured or initialization failed.

func Go

func Go(fn func(), errFn func(error))

Go 包裹一个函数,捕获 panic 并调用错误处理函数。

func ListenAndServe

func ListenAndServe(sevCfg *ServerConfig) error

Run starts the HTTP server on the given address.

func Run

func Run(app App) error

Run starts the engine.

func ValidateStruct

func ValidateStruct(dst any) error

ValidateStruct validates struct fields using `validate:"..."` rules and optional `msg:"rule=message;rule2=message2"`. Supported rules: required, min, max, len, email, eq, gt, lt, ge, le, password, phone, regex, date, datetime, idcard.

func WrapError

func WrapError(msg string, err error) error

WrapError 包裹一个错误,附加错误消息与可选敏感日志(第三个参数可不传)。 可多次调用以形成错误链路:WrapError(WrapError(err, "m1"), "m2", "s2")。

Types

type App

type App interface {
	// Name returns the project name.
	Name() string
	// Install runs on first startup when install.lock is missing.
	Install(ctx *HwfCtx) error
	// Route registers module routes.
	Route(r Router)
	// Init runs on every startup.
	Init(ctx *HwfCtx) error
	// Modules returns all modules to register.
	Modules() []Module
	// Config returns a pointer to the project's configuration struct.
	Config() any
}

type AppJSONFormatter

type AppJSONFormatter interface {
	JSONFormat(ctx *ReqCtx, v ...any)
}

JSONFormatter is the interface to format JSON output.

type AppPackResourcer

type AppPackResourcer interface {
	PackResource() *embed.FS
}

PackResourcer is the interface to provide resource filesystem.

type AppTLSConfiger

type AppTLSConfiger interface {
	TLSConfig() *tls.Config
}

TLSConfiger is the interface to provide TLS config.

type ConfigFiler

type ConfigFiler interface {
	ConfigFile() string
}

ConfigFiler is the interface to provide config file path.

type Cron

type Cron interface {
	Add(spec string, job func(*HwfCtx))
	Start()
	Stop()
}

CronJob is a cron engine interface.

type CronJob

type CronJob interface {
	Add(spec string, job func(*HwfCtx))
}

CronJob is a cron job interface.

type FieldError

type FieldError struct {
	Field   string
	Rule    string
	Message string
}

type H

type H map[string]any

H 是一个通用的 map 类型,用于存储任意键值对。

type HandlerFunc

type HandlerFunc func(*ReqCtx)

type Hooks

type Hooks interface {
	On(name string, fn HooksFunc)
	Put(name string, ctx *HwfCtx, payload any) error
}

Hooks is the interface for hooks.

type HooksFunc

type HooksFunc func(*HwfCtx, any) error

HooksFunc is the function type for hooks.

type HwfCtx

type HwfCtx struct {
	context.Context
	// contains filtered or unexported fields
}

func NewCtx

func NewCtx() *HwfCtx

func (*HwfCtx) Ctx

func (c *HwfCtx) Ctx() context.Context

Ctx returns the underlying context.Context.

func (*HwfCtx) DB

func (c *HwfCtx) DB() *gorm.DB

DB returns the default gorm.DB directly (simplified).

func (*HwfCtx) DBNamed

func (c *HwfCtx) DBNamed(name string) *gorm.DB

DBNamed returns a named database handle if configured, otherwise the default.

func (*HwfCtx) GetVal

func (c *HwfCtx) GetVal(key string) (any, bool)

Get retrieves a value from the request-scoped storage. Returns (nil, false) if key missing.

func (*HwfCtx) Log

func (c *HwfCtx) Log() *Logger

func (*HwfCtx) NamedRedis

func (c *HwfCtx) NamedRedis(name string) *redis.Client

NamedRedis returns the named Redis client if configured.

func (*HwfCtx) ORM

func (c *HwfCtx) ORM() *ORM

ORM returns the ORM wrapper for advanced helpers like Transaction.

func (*HwfCtx) PageFind

func (c *HwfCtx) PageFind(db *gorm.DB, page int, pageSize int, ptr any) (int64, error)

Page 分页查询 返回总条数和错误信息

func (*HwfCtx) PutHook

func (c *HwfCtx) PutHook(name string, payload any)

PutHook puts a hook payload for the given name in the context.

func (*HwfCtx) Redis

func (c *HwfCtx) Redis() *redis.Client

Redis returns the Redis client if configured.

func (*HwfCtx) Resource

func (c *HwfCtx) Resource() ResourceEngine

Resource returns the resource engine for reading embedded files.

func (*HwfCtx) SetVal

func (c *HwfCtx) SetVal(key string, val any)

Set stores a value in the request-scoped storage.

func (*HwfCtx) StdLog deprecated

func (c *HwfCtx) StdLog() *log.Logger

Deprecated: StdLog for quick logging in examples.

func (*HwfCtx) Transaction

func (c *HwfCtx) Transaction(fn func() error) error

Transaction helper to run fn within a transaction.

type LogLevel

type LogLevel int
const (
	LevelOff LogLevel = iota
	LevelError
	LevelWarn
	LevelInfo
	LevelDebug
)

type Logger

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

func GetLogger

func GetLogger() *Logger

func (*Logger) Debugf

func (l *Logger) Debugf(format string, v ...any)

Debugf logs formatted debug messages.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, v ...any)

Errorf logs formatted error messages.

func (*Logger) Infof

func (l *Logger) Infof(format string, v ...any)

Infof logs formatted debug messages.

func (*Logger) Println

func (l *Logger) Println(v ...any)

Println logs a message.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, v ...any)

Warnf logs formatted warning messages.

type Module

type Module interface {
	// Name returns the module name.
	Name() string
	// Install runs on first startup when install.lock is missing.
	Install(ctx *HwfCtx) error
	// Init runs on every startup.
	Init(ctx *HwfCtx) error
	// Models returns GORM model structs used to auto-create tables.
	Models() []any
	// Route registers module routes.
	Route(r Router)
	// Cron returns cron jobs definitions.
	Cron(c CronJob)
	// Triggers returns hook names module may trigger.
	Triggers(h Hooks)
	// Config returns a pointer to the module's configuration struct.
	Config() any // module specific configuration struct pointer
}

type ORM

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

func GetNamedORM

func GetNamedORM(name string) *ORM

func GetORM

func GetORM() *ORM

func (*ORM) DB

func (o *ORM) DB() *gorm.DB

func (*ORM) Transaction

func (o *ORM) Transaction(fn func() error) error

Transaction 执行一个函数,如果当前不在事务中则开启新事务,否则复用当前事务。 如果函数返回错误,事务会被回滚;否则提交。 注意:如果已经在事务中,函数执行失败不会自动回滚,需要外层事务处理。

type ReqCtx

type ReqCtx struct {
	*HwfCtx // framework context
	W       http.ResponseWriter
	R       *http.Request
	// contains filtered or unexported fields
}

ReqCtx provides request-scoped helpers.

func NewTestReqCtx

func NewTestReqCtx(w http.ResponseWriter, r *http.Request) *ReqCtx

NewTestReqCtx creates a ReqCtx for testing purposes

func (*ReqCtx) Abort

func (c *ReqCtx) Abort()

Abort stops the execution of subsequent handlers in the chain.

func (*ReqCtx) AbortWithStatus

func (c *ReqCtx) AbortWithStatus(code int)

AbortWithStatus aborts the request and sets the HTTP status code.

func (*ReqCtx) AbortWithStatusJSON

func (c *ReqCtx) AbortWithStatusJSON(code int, v any)

AbortWithStatusJSON aborts the request, sets the HTTP status code, and sends a JSON response.

func (*ReqCtx) Aborted

func (c *ReqCtx) Aborted() bool

Aborted returns whether the request has been aborted.

func (*ReqCtx) BindForm

func (c *ReqCtx) BindForm(dst any) error

BindForm binds form (for POST with application/x-www-form-urlencoded) with enhanced type conversion and slice support.

func (*ReqCtx) BindHeader

func (c *ReqCtx) BindHeader(dst any) error

BindHeader binds headers with enhanced type conversion and slice support.

func (*ReqCtx) BindJSON

func (c *ReqCtx) BindJSON(dst any) error

BindJSON binds JSON body to struct with type conversion and validates.

func (*ReqCtx) BindQuery

func (c *ReqCtx) BindQuery(dst any) error

BindQuery binds URL query parameters with enhanced type conversion and slice support.

func (*ReqCtx) Bytes

func (c *ReqCtx) Bytes(code int, b []byte)

Bytes serves a byte array with the specified status code.

func (*ReqCtx) ClientIP

func (c *ReqCtx) ClientIP() string

ClientIP helper

func (*ReqCtx) Cookie

func (c *ReqCtx) Cookie(name string) (string, error)

Cookie gets the cookie value for the given name.

func (*ReqCtx) Ctx

func (c *ReqCtx) Ctx() *HwfCtx

func (*ReqCtx) Form

func (c *ReqCtx) Form(key string) string

Form returns the form parameter value for the given key.

func (*ReqCtx) GetHeader

func (c *ReqCtx) GetHeader(key string) string

GetHeader helper

func (*ReqCtx) GetRawData

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

GetRawData reads the raw request body data.

func (*ReqCtx) HTML

func (c *ReqCtx) HTML(code int, html string)

func (*ReqCtx) JSON

func (c *ReqCtx) JSON(code int, v any)

func (*ReqCtx) JSONF

func (c *ReqCtx) JSONF(v ...any)

JSONF 使用 App.FormatJSON 对输出进行统一包装;未配置时回退到默认 JSON 输出。 如果应用未实现 AppJSONFormatter 接口,将使用默认的 JSON 格式输出。

func (*ReqCtx) Next

func (c *ReqCtx) Next()

Next executes the next handler in the middleware chain. It should be called within middleware functions to continue processing the request.

func (*ReqCtx) Param

func (c *ReqCtx) Param(key string, dest any) error

Param gets path parameter by key and assigns it to the provided pointer. Supported types: string, int, int64, uint, uint64, float32, float64, bool Example: c.Param("id", &id)

func (*ReqCtx) Proxy

func (c *ReqCtx) Proxy(target string, setfn func(*httputil.ReverseProxy)) error

Proxy forwards the current request to the given target using ReverseProxy. Example: c.Proxy("http://localhost:9000/") If you need to strip a prefix, adjust c.R.URL.Path before calling.

func (*ReqCtx) Query

func (c *ReqCtx) Query(key string) string

Query returns the query parameter value for the given key.

func (*ReqCtx) Redirect

func (c *ReqCtx) Redirect(code int, url string)

Redirect helper

func (*ReqCtx) RenderHtml

func (c *ReqCtx) RenderHtml(code int, templateFile string, data any)

RenderHtml renders the specified HTML template with the given data and status code.

func (*ReqCtx) Request

func (c *ReqCtx) Request() *http.Request

Request returns the underlying *http.Request.

func (*ReqCtx) ResponseWriter

func (c *ReqCtx) ResponseWriter() http.ResponseWriter

ResponseWriter returns the underlying http.ResponseWriter.

func (*ReqCtx) SaveUploadedFile

func (c *ReqCtx) SaveUploadedFile(field, dst string) error

SaveUploadedFile saves the uploaded file from a multipart form to the specified destination path.

func (*ReqCtx) ServeFile

func (c *ReqCtx) ServeFile(filePath string)

File helpers

func (*ReqCtx) ServeFileDownload

func (c *ReqCtx) ServeFileDownload(filePath, downloadName string)

ServeFileDownload serves a file for download with the specified name.

func (*ReqCtx) SetCookie

func (c *ReqCtx) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie sets a cookie with the specified name, value, max age, path, domain, secure, and httpOnly.

func (*ReqCtx) SetHandlers

func (c *ReqCtx) SetHandlers(handlers []HandlerFunc)

SetHandlers sets the handler chain for testing

func (*ReqCtx) SetHeader

func (c *ReqCtx) SetHeader(key, value string)

Header helper

func (*ReqCtx) String

func (c *ReqCtx) String(code int, s string)

String serves a string with the specified status code.

type ResourceEngine

type ResourceEngine interface {
	// ReadFile 读取嵌入资源文件内容(相对路径,不可越权)。
	ReadFile(name string) ([]byte, error)
	// Exists 判断资源文件是否存在。
	Exists(name string) bool
	// Handler 返回用于挂载的静态资源处理器(基于当前 ResourceFS)。
	Handler(prefix string) http.Handler
}

type Router

type Router interface {
	GET(path string, h HandlerFunc)
	POST(path string, h HandlerFunc)
	PUT(path string, h HandlerFunc)
	DELETE(path string, h HandlerFunc)
	Any(path string, h HandlerFunc)
	Use(mw ...HandlerFunc)
	Group(prefix string) Router
	Static(prefix, dir string)
	File(path, file string)
}

type RouterEngine

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

func NewRouter

func NewRouter() *RouterEngine

setupRouter initializes the global router engine.

func (*RouterEngine) Any

func (e *RouterEngine) Any(path string, h HandlerFunc)

Any registers a route handler that matches all HTTP methods.

func (*RouterEngine) DELETE

func (e *RouterEngine) DELETE(path string, h HandlerFunc)

DELETE registers a DELETE route handler.

func (*RouterEngine) File

func (e *RouterEngine) File(path, file string)

File serves a single file at the given path.

func (*RouterEngine) GET

func (e *RouterEngine) GET(path string, h HandlerFunc)

GET registers a GET route handler.

func (*RouterEngine) GetPathMW

func (e *RouterEngine) GetPathMW() map[string][]HandlerFunc

GetPathMW returns the path middleware map for testing purposes

func (*RouterEngine) GetRouteMap

func (e *RouterEngine) GetRouteMap() map[string]map[string]HandlerFunc

GetRouteMap returns the route map for testing purposes

func (*RouterEngine) Group

func (e *RouterEngine) Group(prefix string) Router

Group creates a new router group with the given prefix. All routes registered in the group will have the prefix prepended to their paths. The group inherits middleware from the parent router.

func (*RouterEngine) POST

func (e *RouterEngine) POST(path string, h HandlerFunc)

POST registers a POST route handler.

func (*RouterEngine) PUT

func (e *RouterEngine) PUT(path string, h HandlerFunc)

PUT registers a PUT route handler.

func (*RouterEngine) Static

func (e *RouterEngine) Static(prefix, dir string)

Static serves static files from the given directory at the specified prefix.

func (*RouterEngine) Use

func (e *RouterEngine) Use(mw ...HandlerFunc)

Use adds middleware functions to the router. Middleware will be executed in the order they are added.

type ServerConfig

type ServerConfig struct {
	Addr      string
	TLSConfig *tls.Config
	Router    *RouterEngine
}

ServerConfig defines the configuration for the HTTP server.

type ValidationErrors

type ValidationErrors []FieldError

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

Directories

Path Synopsis
cmd
hwf command
middleware
jwt
pkg
hconfig
配置文件的读取和写入 目前仅支持json格式配置文件
配置文件的读取和写入 目前仅支持json格式配置文件

Jump to

Keyboard shortcuts

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