rock

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: MIT Imports: 30 Imported by: 1

README

Rock

CI

一个轻量、易用的 Go Web 框架,基于标准库 net/http,受 ginirislars 启发。

特性

  • 基于 trie 的高性能路由:命名参数 :id、通配符 :name*、正则参数 :id(\d+)、尾斜杠/固定路径自动重定向
  • 路由分组 + per-group 中间件与 404/405 处理
  • 请求上下文(Context)统一封装:响应、参数、绑定、上传、日志
  • 内置 ShouldBind 请求绑定与 go-playground/validator 校验
  • 文件上传(大小/扩展名/MIME 校验、唯一文件名、请求体上限防护)
  • 统一错误响应格式,生产环境不泄露内部细节
  • 可插拔的视图引擎(默认配合 rock-pongo2
  • 优雅关闭与 HTTPS(TLS)
  • 基于 sync.Pool 的对象复用,零额外依赖的性能设计

安装

go get github.com/go-rock/rock

Go 版本要求:>= 1.17

快速开始

package main

import "github.com/go-rock/rock"

func main() {
	app := rock.New()
	app.Use(rock.Recovery())

	app.Get("/", func(c rock.Context) {
		c.JSON(200, rock.M{"message": "hello rock"})
	})

	app.Run(":8989") // 阻塞运行,Ctrl-C 优雅退出
}

路由

基础路由
app.Get("/users", listUsers)
app.Post("/users", createUser)
app.Put("/users/:id", updateUser)
app.Delete("/users/:id", deleteUser)
app.Patch("/users/:id", patchUser)
app.Options("/users", preflight)
参数路由
语法 说明 示例
:name 命名参数 /users/:id 匹配 /users/42
:name* 通配符(捕获剩余路径) /files/:path* 匹配 /files/a/b.txt
:name(regexp) 正则参数 /users/:id(\d+) 只匹配数字 id
::name 字面量 :name /x/::id 只匹配 /x/:id
:name+suffix 后缀参数 /a/:file+.json 匹配 /a/data.json
app.Get("/users/:id", func(c rock.Context) {
	id := c.Param("id")          // "42"
	uid := c.MustParamInt("id", 0) // 42,失败用默认值 0
})
静态文件
app.Static("/assets", "./static")  // 目录
路由分组

分组可以嵌套,前缀自动拼接;分组级中间件和 404/405 只作用于本分组路径

admin := app.Group("/admin")
admin.Use(authMiddleware())        // 只作用于 /admin 前缀
admin.Get("/login", adminLogin)

// per-group 404:/admin 下未匹配的路径返回 JSON
admin.NoRoute(func(c rock.Context) {
	c.JSON(404, rock.M{"msg": "not found"})
})

// 根分组 404(作用于全局)
app.NoRoute(func(c rock.Context) {
	c.HTML("404")
})

中间件

中间件是 func(rock.Context),通过 c.Next() 继续链路;c.Abort() 终止链路。

func Logger() rock.HandlerFunc {
	return func(c rock.Context) {
		start := time.Now()
		c.Next()
		log.Printf("[%d] %s in %v", c.StatusCode(), c.Request().URL.Path, time.Since(start))
	}
}

app.Use(rock.Recovery(), Logger())

分组中间件按"外层分组先、内层分组后"执行。额外工具方法:

  • group.UseFunc(...) —— 添加 func(Context) 类型中间件
  • group.UseWithPriority(priority, mw) —— 指定位置插入
  • group.RemoveMiddleware(i) / group.ClearMiddleware() —— 移除/清空

内置 rock.Recovery() 恢复 panic 并返回统一的 500 响应。

路由级中间件

中间件可以只绑定到某一条路由(在处理器之前执行),适合"同一分组下有公有有私有"的场景:

g.POST("/login", Login)                            // 公开路由:不挂鉴权
g.GET("/users", ListUser, JWTAuth(secret), RequirePermission(enf)) // 只对该路由挂鉴权

与分组中间件叠加时,执行顺序为:分组中间件 → 路由级中间件 → 处理器

请求上下文

rock.Context 封装了完整的请求/响应能力。

响应
c.JSON(200, rock.M{"ok": true})          // Content-Type: application/json
c.XML(200, obj)
c.String(200, "Hello %s", name)          // text/plain
c.Status(204)                            // 只设状态码(懒写头,可先设后改)
c.SetHeader("X-Custom", "1")
c.Attachment(fileReader, "a.txt")        // 下载
c.Inline(fileReader, "view.txt")         // 内联
请求参数
c.Param("id")            // 路径参数
c.Query("page")          // 查询参数
c.GetQuery("page")       // (值, 是否存在),?page= 视为存在但为空
c.QueryInt("page")       // 查询参数转 int
c.MustPostInt("age", 0)  // 表单参数,带默认值
绑定与校验
type CreateUser struct {
	Name  string `binding:"required"`
	Email string `binding:"required,email"`
}

func createUser(c rock.Context) {
	var req CreateUser
	if err := c.ShouldBind(&req); err != nil { // 按 Content-Type 自动选择 JSON/XML/Form
		c.JSON(400, rock.M{"error": err.Error()})
		return
	}
	// 使用 req...
}

ShouldBind/Decode 同一请求内可重复调用;默认 body 上限 10MB,可通过 c.ShouldBind(&req, false, 5<<20) 调整。

视图数据与渲染
c.Set("user", user)        // 键值数据
c.SetData(rock.M{...})     // 整体数据
c.ViewData("title", "首页") // 视图数据(供模板使用)
c.HTML("home", rock.M{"post": p}) // 渲染模板

文件上传

func upload(c rock.Context) {
	config := &rock.FileUploadConfig{
		MaxFileSize:       10 << 20,          // 单文件 10MB
		MaxTotalSize:      11 << 20,          // 请求体总上限(防 DoS)
		AllowedExtensions: []string{".jpg", ".jpeg", ".png"},
		AllowedMimeTypes:  []string{"image/jpeg", "image/png"},
		SaveDir:           "./uploads",
		GenerateUniqueName: true,
		FilenamePrefix:     "upload_",
	}

	info, err := c.SaveSingleFile("file", config)
	if err != nil {
		c.JSON(400, rock.M{"error": err.Error()})
		return
	}
	c.JSON(200, rock.H{"filename": info.Filename, "path": info.SavedPath})
}

快捷方法:c.UploadSingleImage / c.UploadSingleDocument / c.UploadMultipleImages / c.SaveMultipleFiles。 上传目录如果通过 app.Static 对外服务,注意白名单不要放开 .html/.svg 等可被浏览器执行的类型。

错误处理

统一的错误响应结构:{"success": false, "error": {"code": 400, "message": "...", "detail": "..."}}

rock.WriteError(c, 404, rock.NewAppError(rock.ErrNotFound, "not found"))
rock.WriteSuccess(c, data) // 200 + {"success": true, "data": ...}

// 错误码常量
rock.ErrBadRequest   // 400
rock.ErrUnauthorized // 401
rock.ErrForbidden    // 403
rock.ErrNotFound     // 404
rock.ErrMethodNotAllow // 405
rock.ErrUnprocessable  // 422
rock.ErrInternalServer // 500

ShouldBind 的校验错误会由 WriteError 自动映射为 400 "Validation failed";未知内部错误在生产环境只返回通用文案,细节仅在调试模式(rock.SetDebug(true))下进入 detail

日志

内置 RockLogger,默认开启请求日志:

app.SetLogLevel(rock.LevelDebug)              // Debug < Info < Warn < Error < Fatal
app.EnableRequestLog(false)                   // 关闭请求日志
app.SetLoggerOutput(os.Stdout, file)          // 多输出

// Context 内日志
c.LogInfo("processing %s", c.GetPath())
c.LogError("something failed")

// 全局便捷函数
rock.Info("app started")
rock.Errorf("error: %v", err)

视图引擎

核心不内置模板引擎,通过 ViewEngine 接口插拔。推荐 rock-pongo2(基于 pongo2/Django 语法):

import render "github.com/go-rock/rock-pongo2"

app.RegisterView(render.New(render.ViewConfig{
	ViewDir:   "./views/",
	Extension: ".html",
}))
app.Get("/", func(c rock.Context) {
	c.HTML("home", rock.M{"title": "Home"})
})

配置

app.SetTrustProxy(true)  // 部署在可信反向代理(nginx 等)后时开启,让 ClientIP 读取代理头;默认关闭防伪造
app.SetDebug(true)       // 开启调试输出(路由表、错误细节);生产环境保持关闭
app.SetLogLevel(rock.LevelInfo)

服务器

app.Run()                // 默认 :8989
app.Run(":8080")
app.RunTLS(":8443", "server.crt", "server.key") // HTTPS

Run/RunTLS 阻塞运行,收到 SIGINT/SIGTERM 后等待在途请求最多 5 秒完成再退出。

测试

go test ./...           # 全部测试
go test -race ./...     # 竞态检测
go test -cover ./...    # 覆盖率

项目结构

rock/
├── rock.go        # App:ServeHTTP、中间件收集、服务器(Run/RunTLS)
├── context.go     # Context/Ctx:请求-响应上下文、绑定、上传、视图数据
├── router.go      # Router:路由分发、per-group NoRoute/NoMethod
├── trie/          # trie 前缀树路由引擎(参数/通配符/正则/重定向)
├── group.go       # RouterGroup:分组、中间件管理、路由注册
├── binding/       # 请求绑定与 go-playground/validator 校验
├── upload.go      # 文件上传
├── errors.go      # 统一错误模型
├── logger.go      # 日志
├── recovery.go    # panic 恢复中间件
├── store.go       # 并发安全的键值存储(ctx.Values)
├── config.go      # 配置项
└── debug.go       # 调试开关(SetDebug/IsDebugging)

致谢

许可证

MIT

Documentation

Overview

Package rock 是一个轻量、易用的 Go Web 框架,基于标准库 net/http 构建。 提供基于 trie 的路由(参数/通配符/正则)、中间件、请求绑定与校验、 文件上传、统一错误处理与可插拔的视图引擎。

Index

Constants

View Source
const (
	// CONNECT HTTP method
	CONNECT = http.MethodConnect
	// DELETE HTTP method
	DELETE = http.MethodDelete
	// GET HTTP method
	GET = http.MethodGet
	// HEAD HTTP method
	HEAD = http.MethodHead
	// OPTIONS HTTP method
	OPTIONS = http.MethodOptions
	// PATCH HTTP method
	PATCH = http.MethodPatch
	// POST HTTP method
	POST = http.MethodPost
	// PUT HTTP method
	PUT = http.MethodPut
	// TRACE HTTP method
	TRACE = http.MethodTrace

	ApplicationJSON                  = "application/json"
	ApplicationJSONCharsetUTF8       = ApplicationJSON + "; " + CharsetUTF8
	ApplicationJavaScript            = "application/javascript"
	ApplicationJavaScriptCharsetUTF8 = ApplicationJavaScript + "; " + CharsetUTF8
	ApplicationXML                   = "application/xml"
	ApplicationXMLCharsetUTF8        = ApplicationXML + "; " + CharsetUTF8
	ApplicationForm                  = "application/x-www-form-urlencoded"
	ApplicationProtobuf              = "application/protobuf"
	ApplicationMsgpack               = "application/msgpack"
	TextHTML                         = "text/html"
	TextHTMLCharsetUTF8              = TextHTML + "; " + CharsetUTF8
	TextPlain                        = "text/plain"
	TextPlainCharsetUTF8             = TextPlain + "; " + CharsetUTF8
	MultipartForm                    = "multipart/form-data"
	OctetStream                      = "application/octet-stream"

	CharsetUTF8 = "charset=utf-8"

	AcceptedLanguage   = "Accept-Language"
	AcceptEncoding     = "Accept-Encoding"
	Authorization      = "Authorization"
	ContentDisposition = "Content-Disposition"
	ContentEncoding    = "Content-Encoding"
	ContentLength      = "Content-Length"
	ContentType        = "Content-Type"
	Location           = "Location"
	Upgrade            = "Upgrade"
	Vary               = "Vary"
	WWWAuthenticate    = "WWW-Authenticate"
	XForwardedFor      = "X-Forwarded-For"
	XRealIP            = "X-Real-Ip"
	Allow              = "Allow"
	Origin             = "Origin"

	Gzip = "gzip"
)

HTTP Constant Terms and Variables

Variables

View Source
var CommonErrorMessages = map[ErrorCode]string{
	ErrBadRequest:     "Bad Request",
	ErrUnauthorized:   "Unauthorized",
	ErrForbidden:      "Forbidden",
	ErrNotFound:       "Not Found",
	ErrMethodNotAllow: "Method Not Allowed",
	ErrUnprocessable:  "Unprocessable Entity",
	ErrInternalServer: "Internal Server Error",
	ErrBadGateway:     "Bad Gateway",
}

CommonErrorMessages 通用错误消息

View Source
var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int)

DebugPrintRouteFunc indicates debug log output format.

View Source
var DefaultWriter io.Writer = os.Stdout

DefaultWriter 是调试输出的默认写入目标。

Functions

func Debug added in v0.3.0

func Debug(args ...interface{})

Debug 调试日志

func Debugf added in v0.3.0

func Debugf(format string, args ...interface{})

Debugf 格式化调试日志

func EnsureTemplateName added in v0.2.0

func EnsureTemplateName(s string, v ViewEngine) string

Get filename by viewEngine

func Error added in v0.3.0

func Error(args ...interface{})

Error 错误日志

func Errorf added in v0.3.0

func Errorf(format string, args ...interface{})

Errorf 格式化错误日志

func Fatal added in v0.3.0

func Fatal(args ...interface{})

Fatal 致命错误日志

func Fatalf added in v0.3.0

func Fatalf(format string, args ...interface{})

Fatalf 格式化致命错误日志

func GetCaller added in v0.3.0

func GetCaller() (file string, line int, function string)

GetCaller 获取调用者信息

func GetErrorMessage added in v0.3.0

func GetErrorMessage(code ErrorCode) string

GetErrorMessage 获取错误消息

func GetFileMIMEType added in v0.3.0

func GetFileMIMEType(fh *multipart.FileHeader) (string, error)

GetFileMIMEType 获取文件MIME类型

func HandlePanic added in v0.3.0

func HandlePanic(c Context, message interface{})

HandlePanic 处理panic恢复

func Info added in v0.3.0

func Info(args ...interface{})

Info 信息日志

func Infof added in v0.3.0

func Infof(format string, args ...interface{})

Infof 格式化信息日志

func IsDebugging

func IsDebugging() bool

func SetDebug added in v0.3.0

func SetDebug(enabled bool)

SetDebug 显式开启/关闭调试输出。 测试环境(go test)下 IsDebugging 始终返回 true,不受此开关影响。

func SetDefaultLogger added in v0.3.0

func SetDefaultLogger(logger *RockLogger)

SetDefaultLogger 设置默认日志器

func ValidateFile added in v0.3.0

func ValidateFile(fh *multipart.FileHeader, config *FileUploadConfig) error

ValidateFile 验证文件

func ValidateMIMEType added in v0.3.0

func ValidateMIMEType(fh *multipart.FileHeader, config *FileUploadConfig) error

ValidateMIMEType 验证MIME类型

func Warn added in v0.3.0

func Warn(args ...interface{})

Warn 警告日志

func Warnf added in v0.3.0

func Warnf(format string, args ...interface{})

Warnf 格式化警告日志

func WriteError added in v0.3.0

func WriteError(c Context, statusCode int, err error)

WriteError 写入错误响应

func WriteSuccess added in v0.3.0

func WriteSuccess(c Context, data interface{})

WriteSuccess 写入成功响应

Types

type App

type App struct {
	*RouterGroup
	// contains filtered or unexported fields
}

App 是 rock 框架的核心实例,实现了 http.Handler 接口。 通过 New 创建,用于注册路由、中间件、视图引擎并启动服务。

func New

func New() *App

func (*App) ConfigurationReadOnly added in v0.2.0

func (app *App) ConfigurationReadOnly() *Configuration

ConfigurationReadOnly returns an object which doesn't allow field writing.

func (*App) EnableRequestLog added in v0.3.0

func (app *App) EnableRequestLog(enabled bool)

EnableRequestLog 启用或禁用请求日志

func (*App) GetView added in v0.2.0

func (app *App) GetView() View

GetView 返回视图引擎持有者(View)。

func (*App) Logger added in v0.3.0

func (app *App) Logger() *RockLogger

Logger 配置日志系统

func (*App) RegisterView added in v0.2.0

func (app *App) RegisterView(viewEngine ViewEngine)

func (*App) Run

func (app *App) Run(args ...string) error

Run 启动 HTTP 服务并阻塞,直到收到 SIGINT/SIGTERM 优雅退出。 args[0] 可选,为监听地址,默认 ":8989"。

func (*App) RunTLS added in v0.3.0

func (app *App) RunTLS(addr, certFile, keyFile string) error

RunTLS 以 HTTPS 启动服务(certFile/keyFile 为 PEM 文件路径), 同样支持 SIGINT/SIGTERM 优雅退出。

func (*App) ServeHTTP

func (app *App) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*App) SetDebug added in v0.3.0

func (app *App) SetDebug(enabled bool)

SetDebug 开启/关闭全局调试输出(路由表、debugPrint,以及 WriteError 的 内部错误细节)。生产环境建议保持关闭。测试环境下始终为调试模式。

func (*App) SetLogLevel added in v0.3.0

func (app *App) SetLogLevel(level LogLevel)

SetLogLevel 设置日志级别

func (*App) SetLoggerOutput added in v0.3.0

func (app *App) SetLoggerOutput(outputs ...io.Writer)

SetLoggerOutput 设置日志输出目标

func (*App) SetTrustProxy added in v0.3.0

func (app *App) SetTrustProxy(enabled bool)

SetTrustProxy 控制是否信任反向代理设置的头(X-Real-IP / X-Forwarded-For)。 仅当应用部署在可信反向代理之后时才应开启,默认关闭。

func (*App) View added in v0.2.0

func (app *App) View(writer io.Writer, filename string, bindingData interface{}) error

type AppError added in v0.3.0

type AppError struct {
	Code    ErrorCode `json:"code"`
	Message string    `json:"message"`
	Detail  string    `json:"detail,omitempty"`
}

AppError 应用错误结构

func NewAppError added in v0.3.0

func NewAppError(code ErrorCode, message string) *AppError

NewAppError 创建新的应用错误

func NewAppErrorWithDetail added in v0.3.0

func NewAppErrorWithDetail(code ErrorCode, message, detail string) *AppError

NewAppErrorWithDetail 创建带有详细信息的应用错误

func NewError added in v0.3.0

func NewError(code ErrorCode, format string, args ...interface{}) *AppError

NewError 创建带有格式化消息的应用错误

func (*AppError) Error added in v0.3.0

func (e *AppError) Error() string

Error 实现error接口

type BlockEngine added in v0.2.0

type BlockEngine struct{}

BlockEngine 是预留的空模板引擎类型。

type Configuration added in v0.2.0

type Configuration struct {
	// Defaults to "rock.view.engine".
	ViewEngineContextKey string `ini:"view_engine_context_key" json:"viewEngineContextKey,omitempty" yaml:"ViewEngineContextKey" toml:"ViewEngineContextKey"`
	// ViewLayoutContextKey is the context's values key
	// responsible to store and retrieve(string) the current view layout.
	// A middleware can modify its associated value to change
	// the layout that `ctx.View` will use to render a template.
	//
	// Defaults to "rock.view.layout".
	ViewLayoutContextKey string `ini:"view_layout_context_key" json:"viewLayoutContextKey,omitempty" yaml:"ViewLayoutContextKey" toml:"ViewLayoutContextKey"`
	// ViewDataContextKey is the context's values key
	// responsible to store and retrieve(interface{}) the current view binding data.
	// A middleware can modify its associated value to change
	// the template's data on-fly.
	//
	// Defaults to "rock.view.data".
	ViewDataContextKey string `ini:"view_data_context_key" json:"viewDataContextKey,omitempty" yaml:"ViewDataContextKey" toml:"ViewDataContextKey"`
	// FallbackViewContextKey is the context's values key
	// responsible to store the view fallback information.
	//
	// Defaults to "rock.view.fallback".
	FallbackViewContextKey string `` /* 131-byte string literal not displayed */

	// TrustProxyHeaders 控制 ClientIP 是否信任 X-Real-IP / X-Forwarded-For 头。
	// 仅当应用部署在可信反向代理(nginx/haproxy 等)之后时才应开启;
	// 直接暴露在公网时这些头可被客户端伪造,开启会允许伪造客户端 IP。
	//
	// 默认 false:只使用 RemoteAddr 作为客户端 IP。
	TrustProxyHeaders bool `ini:"trust_proxy_headers" json:"trustProxyHeaders,omitempty" yaml:"TrustProxyHeaders" toml:"TrustProxyHeaders"`
}

Configuration 保存框架的可配置项(视图上下文键、代理信任开关等)。

func DefaultConfiguration added in v0.2.0

func DefaultConfiguration() Configuration

func (*Configuration) GetViewDataContextKey added in v0.2.0

func (c *Configuration) GetViewDataContextKey() string

GetViewDataContextKey returns the ViewDataContextKey field.

func (*Configuration) GetViewEngineContextKey added in v0.2.0

func (c *Configuration) GetViewEngineContextKey() string

GetViewDataContextKey returns the ViewDataContextKey field.

type Context

type Context interface {
	Application() *App
	ResetRequest(r *http.Request)
	Request() *http.Request
	Writer() http.ResponseWriter
	Next()
	// writer
	Write(rawBody []byte) (int, error)
	// response method
	StatusCode() int
	Status(code int)
	SetHeader(key string, value string)
	Fail(code int, err string)
	String(code int, format string, values ...interface{})
	JSON(code int, obj interface{})
	XML(int, interface{}) error
	// request method
	Param(key string) interface{}
	Query(key string) string
	GetQuery(name string) (string, bool)
	QueryInt(key string) int

	ParseForm() error
	ParseMultipartForm(maxMemory int64) error

	ClientIP() (clientIP string)
	GetMethod() string
	GetPath() string
	// render
	// HTML(code int, name string, data interface{})
	ViewEngine(engine ViewEngine)
	HTML(name string, viewData ...interface{})
	Data() M
	SetData(M)
	Set(key string, value interface{})
	Get(key string) (value interface{}, exists bool)

	Values() *Store
	ViewData(key string, value interface{})
	GetViewData() map[string]interface{}

	GetView() View

	// binding
	Decode(v interface{}, args ...interface{}) (err error)
	ShouldBind(v interface{}, args ...interface{}) (err error)
	ShouldBindJSON(v interface{}) error
	ShouldBindQuery(v interface{}) error

	// Methods
	Abort()
	AbortWithStatusJSON(code int, jsonObj interface{})
	Redirect(url string)
	Attachment(r io.Reader, filename string) (err error)
	Inline(r io.Reader, filename string) (err error)
	File(filepath string)

	MustPostInt(key string, d int) int
	MustPostString(key string, d string) string

	MustParamInt(name string, d int) int

	MustQueryInt(name string, d int) int
	MustQueryString(name string, d string) string

	FormFile(name string) (*multipart.FileHeader, error)

	// 文件上传功能
	SaveSingleFile(name string, config *FileUploadConfig) (*FileInfo, error)
	SaveMultipleFiles(name string, config *FileUploadConfig) ([]*FileInfo, error)
	UploadSingleImage(name string) (*FileInfo, error)
	UploadSingleDocument(name string) (*FileInfo, error)
	UploadMultipleImages(name string) ([]*FileInfo, error)

	// 日志功能
	App() *App
	Logger() *RockLogger
	LogDebug(msg string, args ...interface{})
	LogInfo(msg string, args ...interface{})
	LogWarn(msg string, args ...interface{})
	LogError(msg string, args ...interface{})
}

Context 封装单个 HTTP 请求的请求/响应能力, 由框架注入到每个处理函数与中间件中。

type Ctx

type Ctx struct {

	// request info
	Path   string
	Method string
	// contains filtered or unexported fields
}

Ctx 是 Context 接口的默认实现,通过 sync.Pool 复用。

func (*Ctx) Abort

func (c *Ctx) Abort()

func (*Ctx) AbortWithStatusJSON

func (c *Ctx) AbortWithStatusJSON(code int, jsonObj interface{})

AbortWithStatusJSON calls `Abort()` and then `JSON` internally. This method stops the chain, writes the status code and return a JSON body. It also sets the Content-Type as "application/json".

func (*Ctx) App added in v0.3.0

func (c *Ctx) App() *App

App 返回应用实例

func (*Ctx) Application added in v0.3.0

func (c *Ctx) Application() *App

func (*Ctx) Attachment

func (c *Ctx) Attachment(r io.Reader, filename string) (err error)

Attachment is a helper method for returning an attachement file to be downloaded, if you with to open inline see function

func (*Ctx) ClientIP

func (c *Ctx) ClientIP() (clientIP string)

ClientIP implements a best effort algorithm to return the real client IP, it parses X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy. 注意:只有当配置了 TrustProxyHeaders 时才信任这些头, 否则客户端可以伪造它们来绕过基于 IP 的限流/封禁/审计。

func (*Ctx) Data

func (c *Ctx) Data() M

func (*Ctx) Decode

func (c *Ctx) Decode(v interface{}, args ...interface{}) (err error)

Decode takes the request and attempts to discover it's content type via the http headers and then decode the request body into the provided struct. Example if header was "application/json" would decode using json.NewDecoder(io.LimitReader(c.request.Body, maxMemory)).Decode(v).

func (*Ctx) Fail added in v0.2.0

func (c *Ctx) Fail(code int, err string)

func (*Ctx) File added in v0.4.0

func (c *Ctx) File(filepath string)

File 直接返回磁盘上的单个文件, 由 http.ServeFile 处理 Content-Type、Range 请求与 404。

func (*Ctx) FormFile

func (c *Ctx) FormFile(name string) (*multipart.FileHeader, error)

func (*Ctx) Get

func (c *Ctx) Get(key string) (value interface{}, exists bool)

func (*Ctx) GetMethod added in v0.3.0

func (c *Ctx) GetMethod() string

GetMethod 返回请求方法

func (*Ctx) GetPath added in v0.3.0

func (c *Ctx) GetPath() string

GetPath 返回请求路径

func (*Ctx) GetQuery

func (c *Ctx) GetQuery(name string) (string, bool)

func (*Ctx) GetView added in v0.2.0

func (c *Ctx) GetView() View

func (*Ctx) GetViewData added in v0.3.0

func (ctx *Ctx) GetViewData() map[string]interface{}

GetViewData returns the values registered by `context#ViewData`. The return value is `map[string]interface{}`, this means that if a custom struct registered to ViewData then this function will try to parse it to map, if failed then the return value is nil A check for nil is always a good practise if different kind of values or no data are registered via `ViewData`.

Similarly to `viewData := ctx.Values().Get("rock.view.data")` or `viewData := ctx.Values().Get(ctx.Application().ConfigurationReadOnly().GetViewDataContextKey())`.

func (*Ctx) HTML

func (c *Ctx) HTML(name string, viewData ...interface{})

func (*Ctx) Inline

func (c *Ctx) Inline(r io.Reader, filename string) (err error)

Inline is a helper method for returning a file inline to be rendered/opened by the browser

func (*Ctx) JSON

func (c *Ctx) JSON(code int, obj interface{})

func (*Ctx) LogDebug added in v0.3.0

func (c *Ctx) LogDebug(msg string, args ...interface{})

LogDebug 记录调试日志

func (*Ctx) LogError added in v0.3.0

func (c *Ctx) LogError(msg string, args ...interface{})

LogError 记录错误日志

func (*Ctx) LogInfo added in v0.3.0

func (c *Ctx) LogInfo(msg string, args ...interface{})

LogInfo 记录信息日志

func (*Ctx) LogWarn added in v0.3.0

func (c *Ctx) LogWarn(msg string, args ...interface{})

LogWarn 记录警告日志

func (*Ctx) Logger added in v0.3.0

func (c *Ctx) Logger() *RockLogger

Logger 返回应用日志器

func (*Ctx) MustParamInt

func (c *Ctx) MustParamInt(name string, d int) int

func (*Ctx) MustPostInt

func (c *Ctx) MustPostInt(key string, d int) int

func (*Ctx) MustPostString

func (c *Ctx) MustPostString(key, d string) string

func (*Ctx) MustQueryInt

func (c *Ctx) MustQueryInt(name string, d int) int

func (*Ctx) MustQueryString added in v0.3.0

func (c *Ctx) MustQueryString(name string, d string) string

func (*Ctx) Next

func (c *Ctx) Next()

func (*Ctx) Param

func (c *Ctx) Param(key string) interface{}

func (*Ctx) ParseForm

func (c *Ctx) ParseForm() error

ParseForm calls the underlying http.Request ParseForm but also adds the URL params to the request Form as if they were defined as query params i.e. ?id=13&ok=true but does not add the params to the http.Request.URL.RawQuery for SEO purposes

func (*Ctx) ParseMultipartForm

func (c *Ctx) ParseMultipartForm(maxMemory int64) error

ParseMultipartForm calls the underlying http.Request ParseMultipartForm but also adds the URL params to the request Form as if they were defined as query params i.e. ?id=13&ok=true but does not add the params to the http.Request.URL.RawQuery for SEO purposes

func (*Ctx) Query added in v0.2.0

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

func (*Ctx) QueryInt added in v0.2.0

func (c *Ctx) QueryInt(key string) int

func (*Ctx) Redirect

func (c *Ctx) Redirect(url string)

Redirect to

func (*Ctx) Request

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

func (*Ctx) ResetRequest added in v0.3.0

func (c *Ctx) ResetRequest(r *http.Request)

func (*Ctx) SaveMultipleFiles added in v0.3.0

func (c *Ctx) SaveMultipleFiles(name string, config *FileUploadConfig) ([]*FileInfo, error)

func (*Ctx) SaveSingleFile added in v0.3.0

func (c *Ctx) SaveSingleFile(name string, config *FileUploadConfig) (*FileInfo, error)

func (*Ctx) Set

func (c *Ctx) Set(key string, value interface{})

func (*Ctx) SetData

func (c *Ctx) SetData(data M)

set all data

func (*Ctx) SetHeader added in v0.2.0

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

func (*Ctx) ShouldBind added in v0.3.0

func (c *Ctx) ShouldBind(v interface{}, args ...interface{}) (err error)

func (*Ctx) ShouldBindJSON added in v0.4.0

func (c *Ctx) ShouldBindJSON(v interface{}) error

ShouldBindJSON 强制按 JSON 绑定请求体并校验,不依赖 Content-Type。

func (*Ctx) ShouldBindQuery added in v0.4.0

func (c *Ctx) ShouldBindQuery(v interface{}) error

ShouldBindQuery 将 URL 查询参数绑定到结构体并校验。

func (*Ctx) Status

func (c *Ctx) Status(code int)

Status 设置响应状态码,但不会立即写入响应头。 状态码会在首次写入响应体时(见 writeHeader)才真正发送, 因此允许在写出 body 之前多次修改状态码,也不会触发重复的 WriteHeader。

func (*Ctx) StatusCode added in v0.2.0

func (c *Ctx) StatusCode() int

func (*Ctx) String

func (c *Ctx) String(code int, format string, values ...interface{})

func (*Ctx) UploadMultipleImages added in v0.3.0

func (c *Ctx) UploadMultipleImages(name string) ([]*FileInfo, error)

func (*Ctx) UploadSingleDocument added in v0.3.0

func (c *Ctx) UploadSingleDocument(name string) (*FileInfo, error)

func (*Ctx) UploadSingleImage added in v0.3.0

func (c *Ctx) UploadSingleImage(name string) (*FileInfo, error)

func (*Ctx) Values added in v0.3.0

func (ctx *Ctx) Values() *Store

Values returns the current "user" storage. Named path parameters and any optional data can be saved here. This storage, as the whole context, is per-request lifetime.

You can use this function to Set and Get local values that can be used to share information between handlers and middleware.

func (*Ctx) ViewData added in v0.3.0

func (ctx *Ctx) ViewData(key string, value interface{})

Set view data by key and value

func (*Ctx) ViewEngine added in v0.2.0

func (ctx *Ctx) ViewEngine(engine ViewEngine)

func (*Ctx) Write added in v0.2.0

func (ctx *Ctx) Write(rawBody []byte) (int, error)

Body (raw) Writers

func (*Ctx) Writer added in v0.2.0

func (c *Ctx) Writer() http.ResponseWriter

func (*Ctx) XML

func (c *Ctx) XML(code int, i interface{}) (err error)

XML marshals provided interface + returns XML + status code

type Engine added in v0.2.0

type Engine = ViewEngine

Engine 是 ViewEngine 的别名。

type Entry added in v0.2.0

type Entry struct {
	Key      string      `json:"key" msgpack:"key" yaml:"Key" toml:"Value"`
	ValueRaw interface{} `json:"value" msgpack:"value" yaml:"Value" toml:"Value"`
	// contains filtered or unexported fields
}

Entry 是 Store 中的一条键值记录。 immutable 为 true 时,读取会返回值的深拷贝,外部修改不影响存储。

func (Entry) Value added in v0.2.0

func (e Entry) Value() interface{}

Value 返回条目的值;对 immutable 条目返回深拷贝。

type ErrorCode added in v0.3.0

type ErrorCode int

ErrorCode 定义常见的错误代码

const (
	// 4xx 客户端错误
	ErrBadRequest     ErrorCode = 400
	ErrUnauthorized   ErrorCode = 401
	ErrForbidden      ErrorCode = 403
	ErrNotFound       ErrorCode = 404
	ErrMethodNotAllow ErrorCode = 405
	ErrUnprocessable  ErrorCode = 422

	// 5xx 服务器错误
	ErrInternalServer ErrorCode = 500
	ErrBadGateway     ErrorCode = 502
)

type ErrorResponse added in v0.3.0

type ErrorResponse struct {
	Success bool      `json:"success"`
	Error   HTTPError `json:"error"`
}

ErrorResponse 统一的错误响应格式

type FileInfo added in v0.3.0

type FileInfo struct {
	Header     *multipart.FileHeader `json:"header"`
	Filename   string                `json:"filename"`
	Extension  string                `json:"extension"`
	Size       int64                 `json:"size"`
	MIMEType   string                `json:"mime_type"`
	SavedPath  string                `json:"saved_path,omitempty"`
	URL        string                `json:"url,omitempty"`
	UploadTime time.Time             `json:"upload_time"`
}

FileInfo 文件信息

func SaveMultipleFiles added in v0.3.0

func SaveMultipleFiles(c Context, name string, config *FileUploadConfig) ([]*FileInfo, error)

SaveMultipleFiles 保存多个文件

func SaveSingleFile added in v0.3.0

func SaveSingleFile(c Context, name string, config *FileUploadConfig) (*FileInfo, error)

SaveSingleFile 保存单个文件

func UploadMultipleImages added in v0.3.0

func UploadMultipleImages(c Context, name string) ([]*FileInfo, error)

UploadMultipleImages 上传多张图片

func UploadSingleDocument added in v0.3.0

func UploadSingleDocument(c Context, name string) (*FileInfo, error)

UploadSingleDocument 上传单个文档

func UploadSingleImage added in v0.3.0

func UploadSingleImage(c Context, name string) (*FileInfo, error)

UploadSingleImage 上传单张图片

type FileUploadConfig added in v0.3.0

type FileUploadConfig struct {
	// 文件大小限制 (字节)
	MaxFileSize int64

	// 整个请求体的大小上限 (字节)。
	// 0 表示按 MaxFileSize 的 10 倍 + 1MB 自动计算。
	// 用于在解析 multipart 前就限制请求体大小,防止超大 body 打满内存/磁盘。
	MaxTotalSize int64

	// 允许的文件类型
	AllowedExtensions []string

	// 允许的MIME类型
	AllowedMimeTypes []string

	// 保存目录
	SaveDir string

	// 是否生成唯一文件名
	GenerateUniqueName bool

	// 文件名前缀
	FilenamePrefix string
}

FileUploadConfig 文件上传配置

func DefaultFileUploadConfig added in v0.3.0

func DefaultFileUploadConfig() *FileUploadConfig

DefaultFileUploadConfig 获取默认文件上传配置

type H added in v0.2.0

type H Map

H 是 map[string]interface{} 的别名,常用于 JSON 响应数据。

type HTTPError added in v0.3.0

type HTTPError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Detail  string `json:"detail,omitempty"`
}

HTTPError HTTP错误响应结构

type Handler

type Handler = HandlerFunc

Handler 是 HandlerFunc 的别名。

type HandlerFunc

type HandlerFunc func(Context)

HandlerFunc 定义路由处理函数与中间件的签名。

func GetUploadHandler added in v0.3.0

func GetUploadHandler(config *FileUploadConfig) HandlerFunc

GetUploadHandler 获取文件上传处理器

func Recovery added in v0.2.0

func Recovery() HandlerFunc

Recovery 中间件:处理panic恢复

type HandlersChain

type HandlersChain []HandlerFunc

HandlersChain 是一组按顺序执行的处理器(中间件 + 路由处理器)。

func (HandlersChain) Last added in v0.2.0

func (c HandlersChain) Last() HandlerFunc

Last 返回链上的最后一个处理器,即主处理器。

type LogLevel added in v0.3.0

type LogLevel int

LogLevel 日志级别

const (
	LevelDebug LogLevel = iota
	LevelInfo
	LevelWarn
	LevelError
	LevelFatal
)

func (LogLevel) String added in v0.3.0

func (l LogLevel) String() string

String 实现Stringer接口

type Logger

type Logger interface {
	Debug(args ...interface{})
	Debugf(format string, args ...interface{})
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	Warn(args ...interface{})
	Warnf(format string, args ...interface{})
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})

	// 设置日志级别
	SetLevel(level LogLevel)
	GetLevel() LogLevel

	// 添加输出目标
	AddOutput(output io.Writer)

	// 请求日志
	RequestLog(method, path, ip, userAgent string, statusCode int, latency time.Duration)
}

Logger 日志器接口

type LoggerWithCaller added in v0.3.0

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

WithCaller 带调用者信息的日志记录器

func WrapLoggerWithCaller added in v0.3.0

func WrapLoggerWithCaller(logger Logger) *LoggerWithCaller

WrapLoggerWithCaller 包装日志器以包含调用者信息

func (*LoggerWithCaller) AddOutput added in v0.3.0

func (lc *LoggerWithCaller) AddOutput(output io.Writer)

AddOutput 添加输出目标

func (*LoggerWithCaller) Debug added in v0.3.0

func (lc *LoggerWithCaller) Debug(args ...interface{})

Debug 带调用者信息的调试日志

func (*LoggerWithCaller) Debugf added in v0.3.0

func (lc *LoggerWithCaller) Debugf(format string, args ...interface{})

Debugf 带调用者信息的格式化调试日志

func (*LoggerWithCaller) Error added in v0.3.0

func (lc *LoggerWithCaller) Error(args ...interface{})

Error 带调用者信息的错误日志

func (*LoggerWithCaller) Errorf added in v0.3.0

func (lc *LoggerWithCaller) Errorf(format string, args ...interface{})

Errorf 带调用者信息的格式化错误日志

func (*LoggerWithCaller) Fatal added in v0.3.0

func (lc *LoggerWithCaller) Fatal(args ...interface{})

Fatal 带调用者信息的致命错误日志

func (*LoggerWithCaller) Fatalf added in v0.3.0

func (lc *LoggerWithCaller) Fatalf(format string, args ...interface{})

Fatalf 带调用者信息的格式化致命错误日志

func (*LoggerWithCaller) GetLevel added in v0.3.0

func (lc *LoggerWithCaller) GetLevel() LogLevel

GetLevel 获取日志级别

func (*LoggerWithCaller) Info added in v0.3.0

func (lc *LoggerWithCaller) Info(args ...interface{})

Info 带调用者信息的信息日志

func (*LoggerWithCaller) Infof added in v0.3.0

func (lc *LoggerWithCaller) Infof(format string, args ...interface{})

Infof 带调用者信息的格式化信息日志

func (*LoggerWithCaller) RequestLog added in v0.3.0

func (lc *LoggerWithCaller) RequestLog(method, path, ip, userAgent string, statusCode int, latency time.Duration)

RequestLog 记录请求日志

func (*LoggerWithCaller) SetLevel added in v0.3.0

func (lc *LoggerWithCaller) SetLevel(level LogLevel)

SetLevel 设置日志级别

func (*LoggerWithCaller) Warn added in v0.3.0

func (lc *LoggerWithCaller) Warn(args ...interface{})

Warn 带调用者信息的警告日志

func (*LoggerWithCaller) Warnf added in v0.3.0

func (lc *LoggerWithCaller) Warnf(format string, args ...interface{})

Warnf 带调用者信息的格式化警告日志

type M

type M Map

M 是 map[string]interface{} 的别名,常用于视图数据与通用 KV。

type Map added in v0.2.0

type Map map[string]interface{}

Map 是 map[string]interface{} 的别名,用于路径参数与通用键值数据。

type MiddlewareFunc added in v0.2.0

type MiddlewareFunc = HandlerFunc

MiddlewareFunc 是 HandlerFunc 的别名,语义上表示中间件。

type PreMiddlewareFunc added in v0.2.0

type PreMiddlewareFunc = HandlerFunc

PreMiddlewareFunc 是 HandlerFunc 的别名,语义上表示前置中间件。

type RockLogger added in v0.3.0

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

RockLogger Rock框架的日志器实现

func GetDefaultLogger added in v0.3.0

func GetDefaultLogger() *RockLogger

GetDefaultLogger 获取默认日志器

func NewLogger added in v0.3.0

func NewLogger() *RockLogger

NewLogger 创建新的日志器

func NewLoggerWithConfig added in v0.3.0

func NewLoggerWithConfig(level LogLevel, outputs []io.Writer, enableRequestLog bool) *RockLogger

NewLoggerWithConfig 使用配置创建日志器

func (*RockLogger) AddOutput added in v0.3.0

func (rl *RockLogger) AddOutput(output io.Writer)

AddOutput 添加输出目标

func (*RockLogger) Debug added in v0.3.0

func (rl *RockLogger) Debug(args ...interface{})

Debug 调试日志

func (*RockLogger) Debugf added in v0.3.0

func (rl *RockLogger) Debugf(format string, args ...interface{})

Debugf 格式化调试日志

func (*RockLogger) EnableRequestLog added in v0.3.0

func (rl *RockLogger) EnableRequestLog(enabled bool)

EnableRequestLog 启用或禁用请求日志

func (*RockLogger) Error added in v0.3.0

func (rl *RockLogger) Error(args ...interface{})

Error 错误日志

func (*RockLogger) Errorf added in v0.3.0

func (rl *RockLogger) Errorf(format string, args ...interface{})

Errorf 格式化错误日志

func (*RockLogger) Fatal added in v0.3.0

func (rl *RockLogger) Fatal(args ...interface{})

Fatal 致命错误日志

func (*RockLogger) Fatalf added in v0.3.0

func (rl *RockLogger) Fatalf(format string, args ...interface{})

Fatalf 格式化致命错误日志

func (*RockLogger) GetLevel added in v0.3.0

func (rl *RockLogger) GetLevel() LogLevel

GetLevel 获取日志级别

func (*RockLogger) Info added in v0.3.0

func (rl *RockLogger) Info(args ...interface{})

Info 信息日志

func (*RockLogger) Infof added in v0.3.0

func (rl *RockLogger) Infof(format string, args ...interface{})

Infof 格式化信息日志

func (*RockLogger) RequestLog added in v0.3.0

func (rl *RockLogger) RequestLog(method, path, ip, userAgent string, statusCode int, latency time.Duration)

RequestLog 记录请求日志

func (*RockLogger) SetCallerInfo added in v0.3.0

func (rl *RockLogger) SetCallerInfo(enabled bool)

SetCallerInfo 设置是否包含调用者信息

func (*RockLogger) SetLevel added in v0.3.0

func (rl *RockLogger) SetLevel(level LogLevel)

SetLevel 设置日志级别

func (*RockLogger) SetOutputs added in v0.3.0

func (rl *RockLogger) SetOutputs(outputs ...io.Writer)

SetOutputs 设置输出目标

func (*RockLogger) Warn added in v0.3.0

func (rl *RockLogger) Warn(args ...interface{})

Warn 警告日志

func (*RockLogger) Warnf added in v0.3.0

func (rl *RockLogger) Warnf(format string, args ...interface{})

Warnf 格式化警告日志

type Router

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

Mux is a tire base HTTP request router which can be used to dispatch requests to different handler functions.

func NewRouter added in v0.2.0

func NewRouter(opts ...trie.Options) *Router

New returns a Mux instance.

func (*Router) Handle

func (r *Router) Handle(method, pattern string, handler interface{}) error

type RouterGroup added in v0.2.0

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

RouterGroup 用于组织路由:支持前缀、中间件、嵌套分组, 以及 per-group 的 404/405 处理。

func (*RouterGroup) ClearMiddleware added in v0.3.0

func (group *RouterGroup) ClearMiddleware()

ClearMiddleware 清除所有中间件

func (*RouterGroup) Delete added in v0.3.0

func (group *RouterGroup) Delete(pattern string, handler HandlerFunc, mws ...HandlerFunc)

Delete 注册一条 DELETE 路由,可附带只作用于该路由的中间件。

func (*RouterGroup) Get added in v0.2.0

func (group *RouterGroup) Get(pattern string, handler HandlerFunc, mws ...HandlerFunc)

Get 注册一条 GET 路由,可附带只作用于该路由的中间件。

func (*RouterGroup) Group added in v0.2.0

func (group *RouterGroup) Group(prefix string) *RouterGroup

Group 创建并返回一个前缀为该分组前缀 + prefix 的子分组。

func (*RouterGroup) NoMethod added in v0.2.0

func (group *RouterGroup) NoMethod(handler HandlerFunc)

NoMethod 为当前分组注册 405 处理函数,作用范围同 NoRoute。

func (*RouterGroup) NoRoute added in v0.2.0

func (group *RouterGroup) NoRoute(handler HandlerFunc)

NoRoute 为当前分组及其子路径注册 404 处理函数(per-group)。 与全局 NoRoute 不同,它只作用于匹配该分组 prefix 的路径; 未命中任何注册了 NoRoute 的分组时,回退到根分组(app.NoRoute)。

func (*RouterGroup) Options added in v0.3.0

func (group *RouterGroup) Options(pattern string, handler HandlerFunc, mws ...HandlerFunc)

Options 注册一条 OPTIONS 路由,可附带只作用于该路由的中间件。

func (*RouterGroup) Patch added in v0.3.0

func (group *RouterGroup) Patch(pattern string, handler HandlerFunc, mws ...HandlerFunc)

Patch 注册一条 PATCH 路由,可附带只作用于该路由的中间件。

func (*RouterGroup) Post added in v0.2.0

func (group *RouterGroup) Post(pattern string, handler HandlerFunc, mws ...HandlerFunc)

Post 注册一条 POST 路由,可附带只作用于该路由的中间件。

func (*RouterGroup) Put added in v0.3.0

func (group *RouterGroup) Put(pattern string, handler HandlerFunc, mws ...HandlerFunc)

Put 注册一条 PUT 路由,可附带只作用于该路由的中间件。

func (*RouterGroup) RegisterView added in v0.2.0

func (group *RouterGroup) RegisterView(viewEngine ViewEngine)

func (*RouterGroup) RemoveMiddleware added in v0.3.0

func (group *RouterGroup) RemoveMiddleware(index int)

RemoveMiddleware 移除指定索引的中间件

func (*RouterGroup) SetRender added in v0.2.0

func (group *RouterGroup) SetRender(render ViewEngine)

func (*RouterGroup) Static added in v0.2.0

func (group *RouterGroup) Static(relativePath string, root string)

serve static files

func (*RouterGroup) Use added in v0.2.0

func (group *RouterGroup) Use(middlewares ...HandlerFunc)

Use 为本分组添加中间件,作用于匹配该分组前缀的路径。

func (*RouterGroup) UseFunc added in v0.3.0

func (group *RouterGroup) UseFunc(middlewares ...func(Context))

UseFunc 添加函数类型的中间件

func (*RouterGroup) UseWithPriority added in v0.3.0

func (group *RouterGroup) UseWithPriority(priority int, middleware HandlerFunc)

UseWithPriority 添加带优先级的中间件

type Store added in v0.2.0

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

Store 保持与现有代码的兼容性,但添加性能优化

func NewStore added in v0.3.0

func NewStore() *Store

创建新的Store实例

func (*Store) Get added in v0.2.0

func (r *Store) Get(key string) interface{}

Get returns the entry's value based on its key. If not found returns nil.

func (*Store) GetDefault added in v0.2.0

func (r *Store) GetDefault(key string, def interface{}) interface{}

GetDefault returns the entry's value based on its key. If not found returns "def". This function checks for immutability as well, the rest don't.

func (*Store) GetEntry added in v0.2.0

func (r *Store) GetEntry(key string) (Entry, bool)

GetEntry 线程安全地返回 key 对应的条目副本。 如果没有找到则返回空的 Entry 和 false。

func (*Store) Save added in v0.2.0

func (r *Store) Save(key string, value interface{}, immutable bool) (Entry, bool)

Save 保存键值条目;immutable 为 true 时读取返回深拷贝。

func (*Store) Set added in v0.2.0

func (r *Store) Set(key string, value interface{}) (Entry, bool)

type ValidationError added in v0.3.0

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
	Value   string `json:"value,omitempty"`
}

ValidationError 验证错误

func (*ValidationError) Error added in v0.3.0

func (e *ValidationError) Error() string

type ValueSetter added in v0.2.0

type ValueSetter interface {
	Set(key string, newValue interface{}) (Entry, bool)
}

ValueSetter 表示可以写入键值条的接口。

type View added in v0.2.0

type View struct {
	Engine ViewEngine
}

View 持有当前注册的模板引擎。

func (*View) ExecuteWriter added in v0.2.0

func (v *View) ExecuteWriter(w io.Writer, filename string, bindingData interface{}) error

ExecuteWriter calls the correct view Engine's ExecuteWriter func

func (*View) Register added in v0.2.0

func (v *View) Register(e Engine)

Register registers a view engine.

func (*View) Registered added in v0.2.0

func (v *View) Registered() bool

Registered reports whether an engine was registered.

type ViewEngine added in v0.2.0

type ViewEngine interface {
	Name() string
	Ext() string
	ExecuteWriter(writer io.Writer, filename string, bindingData interface{}) error
	SetViewDir(viewDir string)
	GetViewDir() string
}

ViewEngine 是模板引擎需要实现的接口, 由外部引擎(如 rock-pongo2)提供实现并通过 RegisterView 注册。

Directories

Path Synopsis
Modify from https://github.com/teambition/trie-mux
Modify from https://github.com/teambition/trie-mux

Jump to

Keyboard shortcuts

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