Documentation
¶
Overview ¶
Package rock 是一个轻量、易用的 Go Web 框架,基于标准库 net/http 构建。 提供基于 trie 的路由(参数/通配符/正则)、中间件、请求绑定与校验、 文件上传、统一错误处理与可插拔的视图引擎。
Index ¶
- Constants
- Variables
- func Debug(args ...interface{})
- func Debugf(format string, args ...interface{})
- func EnsureTemplateName(s string, v ViewEngine) string
- func Error(args ...interface{})
- func Errorf(format string, args ...interface{})
- func Fatal(args ...interface{})
- func Fatalf(format string, args ...interface{})
- func GetCaller() (file string, line int, function string)
- func GetErrorMessage(code ErrorCode) string
- func GetFileMIMEType(fh *multipart.FileHeader) (string, error)
- func HandlePanic(c Context, message interface{})
- func Info(args ...interface{})
- func Infof(format string, args ...interface{})
- func IsDebugging() bool
- func SetDebug(enabled bool)
- func SetDefaultLogger(logger *RockLogger)
- func ValidateFile(fh *multipart.FileHeader, config *FileUploadConfig) error
- func ValidateMIMEType(fh *multipart.FileHeader, config *FileUploadConfig) error
- func Warn(args ...interface{})
- func Warnf(format string, args ...interface{})
- func WriteError(c Context, statusCode int, err error)
- func WriteSuccess(c Context, data interface{})
- type App
- func (app *App) ConfigurationReadOnly() *Configuration
- func (app *App) EnableRequestLog(enabled bool)
- func (app *App) GetView() View
- func (app *App) Logger() *RockLogger
- func (app *App) RegisterView(viewEngine ViewEngine)
- func (app *App) Run(args ...string) error
- func (app *App) RunTLS(addr, certFile, keyFile string) error
- func (app *App) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (app *App) SetDebug(enabled bool)
- func (app *App) SetLogLevel(level LogLevel)
- func (app *App) SetLoggerOutput(outputs ...io.Writer)
- func (app *App) SetTrustProxy(enabled bool)
- func (app *App) View(writer io.Writer, filename string, bindingData interface{}) error
- type AppError
- type BlockEngine
- type Configuration
- type Context
- type Ctx
- func (c *Ctx) Abort()
- func (c *Ctx) AbortWithStatusJSON(code int, jsonObj interface{})
- func (c *Ctx) App() *App
- func (c *Ctx) Application() *App
- func (c *Ctx) Attachment(r io.Reader, filename string) (err error)
- func (c *Ctx) ClientIP() (clientIP string)
- func (c *Ctx) Data() M
- func (c *Ctx) Decode(v interface{}, args ...interface{}) (err error)
- func (c *Ctx) Fail(code int, err string)
- func (c *Ctx) File(filepath string)
- func (c *Ctx) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Ctx) Get(key string) (value interface{}, exists bool)
- func (c *Ctx) GetMethod() string
- func (c *Ctx) GetPath() string
- func (c *Ctx) GetQuery(name string) (string, bool)
- func (c *Ctx) GetView() View
- func (ctx *Ctx) GetViewData() map[string]interface{}
- func (c *Ctx) HTML(name string, viewData ...interface{})
- func (c *Ctx) Inline(r io.Reader, filename string) (err error)
- func (c *Ctx) JSON(code int, obj interface{})
- func (c *Ctx) LogDebug(msg string, args ...interface{})
- func (c *Ctx) LogError(msg string, args ...interface{})
- func (c *Ctx) LogInfo(msg string, args ...interface{})
- func (c *Ctx) LogWarn(msg string, args ...interface{})
- func (c *Ctx) Logger() *RockLogger
- func (c *Ctx) MustParamInt(name string, d int) int
- func (c *Ctx) MustPostInt(key string, d int) int
- func (c *Ctx) MustPostString(key, d string) string
- func (c *Ctx) MustQueryInt(name string, d int) int
- func (c *Ctx) MustQueryString(name string, d string) string
- func (c *Ctx) Next()
- func (c *Ctx) Param(key string) interface{}
- func (c *Ctx) ParseForm() error
- func (c *Ctx) ParseMultipartForm(maxMemory int64) error
- func (c *Ctx) Query(key string) string
- func (c *Ctx) QueryInt(key string) int
- func (c *Ctx) Redirect(url string)
- func (c *Ctx) Request() *http.Request
- func (c *Ctx) ResetRequest(r *http.Request)
- func (c *Ctx) SaveMultipleFiles(name string, config *FileUploadConfig) ([]*FileInfo, error)
- func (c *Ctx) SaveSingleFile(name string, config *FileUploadConfig) (*FileInfo, error)
- func (c *Ctx) Set(key string, value interface{})
- func (c *Ctx) SetData(data M)
- func (c *Ctx) SetHeader(key string, value string)
- func (c *Ctx) ShouldBind(v interface{}, args ...interface{}) (err error)
- func (c *Ctx) ShouldBindJSON(v interface{}) error
- func (c *Ctx) ShouldBindQuery(v interface{}) error
- func (c *Ctx) Status(code int)
- func (c *Ctx) StatusCode() int
- func (c *Ctx) String(code int, format string, values ...interface{})
- func (c *Ctx) UploadMultipleImages(name string) ([]*FileInfo, error)
- func (c *Ctx) UploadSingleDocument(name string) (*FileInfo, error)
- func (c *Ctx) UploadSingleImage(name string) (*FileInfo, error)
- func (ctx *Ctx) Values() *Store
- func (ctx *Ctx) ViewData(key string, value interface{})
- func (ctx *Ctx) ViewEngine(engine ViewEngine)
- func (ctx *Ctx) Write(rawBody []byte) (int, error)
- func (c *Ctx) Writer() http.ResponseWriter
- func (c *Ctx) XML(code int, i interface{}) (err error)
- type Engine
- type Entry
- type ErrorCode
- type ErrorResponse
- type FileInfo
- func SaveMultipleFiles(c Context, name string, config *FileUploadConfig) ([]*FileInfo, error)
- func SaveSingleFile(c Context, name string, config *FileUploadConfig) (*FileInfo, error)
- func UploadMultipleImages(c Context, name string) ([]*FileInfo, error)
- func UploadSingleDocument(c Context, name string) (*FileInfo, error)
- func UploadSingleImage(c Context, name string) (*FileInfo, error)
- type FileUploadConfig
- type H
- type HTTPError
- type Handler
- type HandlerFunc
- type HandlersChain
- type LogLevel
- type Logger
- type LoggerWithCaller
- func (lc *LoggerWithCaller) AddOutput(output io.Writer)
- func (lc *LoggerWithCaller) Debug(args ...interface{})
- func (lc *LoggerWithCaller) Debugf(format string, args ...interface{})
- func (lc *LoggerWithCaller) Error(args ...interface{})
- func (lc *LoggerWithCaller) Errorf(format string, args ...interface{})
- func (lc *LoggerWithCaller) Fatal(args ...interface{})
- func (lc *LoggerWithCaller) Fatalf(format string, args ...interface{})
- func (lc *LoggerWithCaller) GetLevel() LogLevel
- func (lc *LoggerWithCaller) Info(args ...interface{})
- func (lc *LoggerWithCaller) Infof(format string, args ...interface{})
- func (lc *LoggerWithCaller) RequestLog(method, path, ip, userAgent string, statusCode int, latency time.Duration)
- func (lc *LoggerWithCaller) SetLevel(level LogLevel)
- func (lc *LoggerWithCaller) Warn(args ...interface{})
- func (lc *LoggerWithCaller) Warnf(format string, args ...interface{})
- type M
- type Map
- type MiddlewareFunc
- type PreMiddlewareFunc
- type RockLogger
- func (rl *RockLogger) AddOutput(output io.Writer)
- func (rl *RockLogger) Debug(args ...interface{})
- func (rl *RockLogger) Debugf(format string, args ...interface{})
- func (rl *RockLogger) EnableRequestLog(enabled bool)
- func (rl *RockLogger) Error(args ...interface{})
- func (rl *RockLogger) Errorf(format string, args ...interface{})
- func (rl *RockLogger) Fatal(args ...interface{})
- func (rl *RockLogger) Fatalf(format string, args ...interface{})
- func (rl *RockLogger) GetLevel() LogLevel
- func (rl *RockLogger) Info(args ...interface{})
- func (rl *RockLogger) Infof(format string, args ...interface{})
- func (rl *RockLogger) RequestLog(method, path, ip, userAgent string, statusCode int, latency time.Duration)
- func (rl *RockLogger) SetCallerInfo(enabled bool)
- func (rl *RockLogger) SetLevel(level LogLevel)
- func (rl *RockLogger) SetOutputs(outputs ...io.Writer)
- func (rl *RockLogger) Warn(args ...interface{})
- func (rl *RockLogger) Warnf(format string, args ...interface{})
- type Router
- type RouterGroup
- func (group *RouterGroup) ClearMiddleware()
- func (group *RouterGroup) Delete(pattern string, handler HandlerFunc, mws ...HandlerFunc)
- func (group *RouterGroup) Get(pattern string, handler HandlerFunc, mws ...HandlerFunc)
- func (group *RouterGroup) Group(prefix string) *RouterGroup
- func (group *RouterGroup) NoMethod(handler HandlerFunc)
- func (group *RouterGroup) NoRoute(handler HandlerFunc)
- func (group *RouterGroup) Options(pattern string, handler HandlerFunc, mws ...HandlerFunc)
- func (group *RouterGroup) Patch(pattern string, handler HandlerFunc, mws ...HandlerFunc)
- func (group *RouterGroup) Post(pattern string, handler HandlerFunc, mws ...HandlerFunc)
- func (group *RouterGroup) Put(pattern string, handler HandlerFunc, mws ...HandlerFunc)
- func (group *RouterGroup) RegisterView(viewEngine ViewEngine)
- func (group *RouterGroup) RemoveMiddleware(index int)
- func (group *RouterGroup) SetRender(render ViewEngine)
- func (group *RouterGroup) Static(relativePath string, root string)
- func (group *RouterGroup) Use(middlewares ...HandlerFunc)
- func (group *RouterGroup) UseFunc(middlewares ...func(Context))
- func (group *RouterGroup) UseWithPriority(priority int, middleware HandlerFunc)
- type Store
- func (r *Store) Get(key string) interface{}
- func (r *Store) GetDefault(key string, def interface{}) interface{}
- func (r *Store) GetEntry(key string) (Entry, bool)
- func (r *Store) Save(key string, value interface{}, immutable bool) (Entry, bool)
- func (r *Store) Set(key string, value interface{}) (Entry, bool)
- type ValidationError
- type ValueSetter
- type View
- type ViewEngine
Constants ¶
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 ¶
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 通用错误消息
var DebugPrintRouteFunc func(httpMethod, absolutePath, handlerName string, nuHandlers int)
DebugPrintRouteFunc indicates debug log output format.
var DefaultWriter io.Writer = os.Stdout
DefaultWriter 是调试输出的默认写入目标。
Functions ¶
func EnsureTemplateName ¶ added in v0.2.0
func EnsureTemplateName(s string, v ViewEngine) string
Get filename by viewEngine
func GetErrorMessage ¶ added in v0.3.0
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 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 WriteError ¶ added in v0.3.0
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 (*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
EnableRequestLog 启用或禁用请求日志
func (*App) RegisterView ¶ added in v0.2.0
func (app *App) RegisterView(viewEngine ViewEngine)
func (*App) RunTLS ¶ added in v0.3.0
RunTLS 以 HTTPS 启动服务(certFile/keyFile 为 PEM 文件路径), 同样支持 SIGINT/SIGTERM 优雅退出。
func (*App) SetDebug ¶ added in v0.3.0
SetDebug 开启/关闭全局调试输出(路由表、debugPrint,以及 WriteError 的 内部错误细节)。生产环境建议保持关闭。测试环境下始终为调试模式。
func (*App) SetLogLevel ¶ added in v0.3.0
SetLogLevel 设置日志级别
func (*App) SetLoggerOutput ¶ added in v0.3.0
SetLoggerOutput 设置日志输出目标
func (*App) SetTrustProxy ¶ added in v0.3.0
SetTrustProxy 控制是否信任反向代理设置的头(X-Real-IP / X-Forwarded-For)。 仅当应用部署在可信反向代理之后时才应开启,默认关闭。
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
NewAppError 创建新的应用错误
func NewAppErrorWithDetail ¶ added in v0.3.0
NewAppErrorWithDetail 创建带有详细信息的应用错误
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) AbortWithStatusJSON ¶
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) Application ¶ added in v0.3.0
func (*Ctx) Attachment ¶
Attachment is a helper method for returning an attachement file to be downloaded, if you with to open inline see function
func (*Ctx) ClientIP ¶
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) Decode ¶
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) File ¶ added in v0.4.0
File 直接返回磁盘上的单个文件, 由 http.ServeFile 处理 Content-Type、Range 请求与 404。
func (*Ctx) GetViewData ¶ added in v0.3.0
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) Inline ¶
Inline is a helper method for returning a file inline to be rendered/opened by the browser
func (*Ctx) MustPostString ¶
func (*Ctx) MustQueryString ¶ added in v0.3.0
func (*Ctx) ParseForm ¶
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 ¶
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) ResetRequest ¶ added in v0.3.0
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) ShouldBind ¶ added in v0.3.0
func (*Ctx) ShouldBindJSON ¶ added in v0.4.0
ShouldBindJSON 强制按 JSON 绑定请求体并校验,不依赖 Content-Type。
func (*Ctx) ShouldBindQuery ¶ added in v0.4.0
ShouldBindQuery 将 URL 查询参数绑定到结构体并校验。
func (*Ctx) Status ¶
Status 设置响应状态码,但不会立即写入响应头。 状态码会在首次写入响应体时(见 writeHeader)才真正发送, 因此允许在写出 body 之前多次修改状态码,也不会触发重复的 WriteHeader。
func (*Ctx) StatusCode ¶ added in v0.2.0
func (*Ctx) UploadMultipleImages ¶ added in v0.3.0
func (*Ctx) UploadSingleDocument ¶ added in v0.3.0
func (*Ctx) UploadSingleImage ¶ added in v0.3.0
func (*Ctx) Values ¶ added in v0.3.0
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) ViewEngine ¶ added in v0.2.0
func (ctx *Ctx) ViewEngine(engine ViewEngine)
func (*Ctx) Writer ¶ added in v0.2.0
func (c *Ctx) Writer() http.ResponseWriter
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 时,读取会返回值的深拷贝,外部修改不影响存储。
type ErrorResponse ¶ added in v0.3.0
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
UploadMultipleImages 上传多张图片
func UploadSingleDocument ¶ added in v0.3.0
UploadSingleDocument 上传单个文档
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 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 HandlerFunc ¶
type HandlerFunc func(Context)
HandlerFunc 定义路由处理函数与中间件的签名。
func GetUploadHandler ¶ added in v0.3.0
func GetUploadHandler(config *FileUploadConfig) HandlerFunc
GetUploadHandler 获取文件上传处理器
type HandlersChain ¶
type HandlersChain []HandlerFunc
HandlersChain 是一组按顺序执行的处理器(中间件 + 路由处理器)。
func (HandlersChain) Last ¶ added in v0.2.0
func (c HandlersChain) Last() HandlerFunc
Last 返回链上的最后一个处理器,即主处理器。
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 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 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) 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) 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.
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 (*Store) Get ¶ added in v0.2.0
Get returns the entry's value based on its key. If not found returns nil.
func (*Store) GetDefault ¶ added in v0.2.0
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.
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
ValueSetter 表示可以写入键值条的接口。
type View ¶ added in v0.2.0
type View struct {
Engine ViewEngine
}
View 持有当前注册的模板引擎。
func (*View) ExecuteWriter ¶ added in v0.2.0
ExecuteWriter calls the correct view Engine's ExecuteWriter func
func (*View) Registered ¶ added in v0.2.0
Registered reports whether an engine was registered.