GoWind 开源生态GoWind 开源生态
首页
框架
GoWind Admin
GoWind CMS
GoWind IM
GoWind UBA
GoWind IoT
GoWind Toolkit
GoWind Quant
GitHub
首页
框架
GoWind Admin
GoWind CMS
GoWind IM
GoWind UBA
GoWind IoT
GoWind Toolkit
GoWind Quant
GitHub
  • 介绍

    • GoWind 框架
    • 框架整体架构
  • go-wind 核心

    • go-wind 核心框架
    • App 生命周期管理
    • Context 传播
    • Transport 抽象
    • Log 门面接口
  • go-wind-plugins 插件

    • go-wind-plugins 插件总览
    • 插件配置系统
    • 插件注册机制(SPI)
    • 日志适配插件
    • 传输协议插件
    • 消息中间件插件
    • 编码解码插件
    • 安全与认证插件
    • 链路追踪插件
    • 缓存插件
    • 对象存储插件(OSS)
    • 限流插件
    • 指标监控插件
    • AI 插件
    • 工作流插件
    • 数据库与缓存插件
    • Bootstrap 集成与网关插件
    • 压缩与序列化插件
    • 模板渲染与验证插件
  • go-wind-bootstrap 启动器

    • go-wind-bootstrap 声明式启动器
    • Bootstrap 配置系统
    • Bootstrap SPI 机制
    • 声明式中间件编排
    • Bootstrap CLI 工具
    • Bootstrap 实战示例
  • 教程

    • 快速入门教程
    • 自定义插件开发教程
    • 多协议同时监听教程
    • 框架迁移指南

模板渲染与验证插件

go-wind-plugins 提供模板渲染和数据验证插件,用于邮件模板、API 参数校验等场景。

一、模板渲染

1.1 适配器列表

适配器导入路径特点
Go Templateplugins/template/gotemplate标准库 text/html template
Handlebarsplugins/template/handlebars灵活的逻辑模板
Jetplugins/template/jet高性能、继承支持

1.2 使用方式

import templatePlugin "github.com/tx7do/go-wind-plugins/template/gotemplate"

renderer := templatePlugin.New(
    templatePlugin.WithRoot("./templates"),
    templatePlugin.WithSuffix(".html"),
    templatePlugin.WithFuncMap(template.FuncMap{
        "formatTime": formatTime,
        "currency":   formatCurrency,
    }),
)

// 渲染模板
output, _ := renderer.Render("email/welcome", map[string]interface{}{
    "UserName": "Alice",
    "VerifyURL": "https://app.example.com/verify?token=abc",
})

1.3 模板继承(Jet)

import jetPlugin "github.com/tx7do/go-wind-plugins/template/jet"

renderer := jetPlugin.New(
    jetPlugin.WithRoot("./views"),
    jetPlugin.WithDevelopmentMode(true),     // 热重载
)
// views/layout.jet
{{block content()}}{{end}}

// views/page.jet
{{extends "layout.jet"}}
{{block content()}}
  <h1>{{.Title}}</h1>
  <p>{{.Content}}</p>
{{end}}

二、数据验证

2.1 适配器

import validatorPlugin "github.com/tx7do/go-wind-plugins/validator"

2.2 结构体验证

type CreateUserRequest struct {
    Username string `json:"username" validate:"required,min=3,max=32"`
    Email    string `json:"email" validate:"required,email"`
    Password string `json:"password" validate:"required,min=8,max=128"`
    Age      int    `json:"age" validate:"gte=18,lte=120"`
    Phone    string `json:"phone" validate:"required,e164"`
}

func handleCreateUser(w http.ResponseWriter, r *http.Request) {
    var req CreateUserRequest
    json.NewDecoder(r.Body).Decode(&req)

    if err := validatorPlugin.Validate(req); err != nil {
        // 返回验证错误
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // 验证通过,处理业务逻辑
}

2.3 验证规则

Tag说明示例
required必填validate:"required"
min / max最小/最大长度validate:"min=3,max=32"
len固定长度validate:"len=11"
gte / lte数值范围validate:"gte=18,lte=120"
email邮箱格式validate:"email"
urlURL 格式validate:"url"
uuidUUID 格式validate:"uuid"
e164手机号validate:"e164"
oneof枚举值validate:"oneof=red green blue"
unique唯一性validate:"unique"
datetime日期时间validate:"datetime=2006-01-02"
ipIP 地址validate:"ip"
uuid4UUID v4validate:"uuid4"

2.4 自定义验证

// 注册自定义验证器
validatorPlugin.RegisterValidation("strong_password", func(fl validator.FieldLevel) bool {
    password := fl.Field().String()
    hasUpper := regexp.MustCompile(`[A-Z]`).MatchString(password)
    hasLower := regexp.MustCompile(`[a-z]`).MatchString(password)
    hasDigit := regexp.MustCompile(`\d`).MatchString(password)
    hasSpecial := regexp.MustCompile(`[!@#$%^&*]`).MatchString(password)
    return hasUpper && hasLower && hasDigit && hasSpecial
})

type RegisterRequest struct {
    Password string `json:"password" validate:"required,strong_password"`
}

2.5 中文错误消息

validatorPlugin.RegisterTranslations("zh", map[string]string{
    "required":       "{0}为必填项",
    "min":            "{0}长度不能少于{1}个字符",
    "max":            "{0}长度不能超过{1}个字符",
    "email":          "{0}格式不正确",
    "gte":            "{0}必须大于或等于{1}",
    "lte":            "{0}必须小于或等于{1}",
    "oneof":          "{0}必须是{1}中的一个",
    "strong_password": "密码必须包含大小写字母、数字和特殊字符",
})

2.6 YAML 配置

validator:
  locale: zh           # zh | en
  custom_rules:
    - name: phone_cn
      regex: "^1[3-9]\\d{9}$"
      message: "手机号格式不正确"

三、国际化(i18n)

import i18nPlugin "github.com/tx7do/go-wind-plugins/i18n"

translator := i18nPlugin.New(
    i18nPlugin.WithLocaleDir("./locales"),
    i18nPlugin.WithDefaultLocale("zh-CN"),
)

// 翻译
msg := translator.T("welcome", map[string]interface{}{
    "name": "Alice",
})
// "欢迎,Alice!"
# locales/zh-CN.yaml
welcome: "欢迎,{name}!"
errors:
  not_found: "资源不存在"
  unauthorized: "未授权"

相关文档

  • 插件配置系统
  • 插件总览
Edit this page
Last Updated:: 6/21/26, 9:28 PM
Contributors: Bobo
Prev
压缩与序列化插件