web

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2020 License: MIT Imports: 32 Imported by: 0

README

web

Copy and delete some functions based on gin.

Documentation

Index

Constants

View Source
const (
	MIMEHTML              = binding.MIMEHTML
	MIMEJSON              = binding.MIMEJSON
	MIMEPlain             = binding.MIMEPlain
	MIMEPOSTForm          = binding.MIMEPOSTForm
	MIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm
	MIMEXML               = binding.MIMEXML
	MIMEXML2              = binding.MIMEXML2
	BodyBytesKey          = "_lierbai/web/bodybyteskey"
)

Content-Type MIME 常见的数据格式.

View Source
const (
	// DebugMode 表示模式是debug.
	DebugMode = "debug"
	// ReleaseMode 表示模式是release.
	ReleaseMode = "release"
	// TestMode 表示模式是test.
	TestMode = "test"
)
View Source
const AuthUserKey = "user"

AuthUserKey 是基本身份验证中用户凭据的cookie名称.

View Source
const BindKey = "_lierbai/web/bindkey"

BindKey 默认绑定键密钥.

View Source
const EnvWebMode = "WEB_MODE"

EnvWebMode 表示web的环境名称.

View Source
const Version = "v1.0.0"

Version 版本号.

Variables

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

DebugPrintRouteFunc 指示调试日志的输出格式.

View Source
var DefaultErrorWriter io.Writer = os.Stderr

DefaultErrorWriter 用来调试错误的默认io.Writer

View Source
var DefaultWriter io.Writer = os.Stdout

DefaultWriter 默认io.Writer用为debug输出或者中间件输出像Logger()和 Recovery(). Logger 和 Recovery 都有自定义的io.Writer输出.

Functions

func Dir

func Dir(root string, listDirectory bool) http.FileSystem

Dir 返回一个可以被http.FileServer()内部使用的http.Filesystem.被用于router.Static(). 假如listDirectory为true,那么它的工作方式与http.Dir()相同. 否则将返回一个.

func DisableBindValidation

func DisableBindValidation()

DisableBindValidation 关闭默认验证器.

func DisableConsoleColor

func DisableConsoleColor()

DisableConsoleColor 禁用颜色输出(终端).

func EnableJsonDecoderDisallowUnknownFields

func EnableJsonDecoderDisallowUnknownFields()

EnableJsonDecoderDisallowUnknownFields 设置为true.用于调用JSON解码器实例上的DisallowUnknownFields方法

func EnableJsonDecoderUseNumber

func EnableJsonDecoderUseNumber()

EnableJsonDecoderUseNumber 设置为true,用于调用JSON解码器实例上的UseNumber方法.

func ForceConsoleColor

func ForceConsoleColor()

ForceConsoleColor 强制颜色输出(终端).

func IsDebugging

func IsDebugging() bool

IsDebugging 如果是框架运行在调式模式,则返回true. 使用SetMode(web.ReleaseMode)禁用调试模式.

func Mode

func Mode() string

Mode 返回当前的模式名称.

func SetMode

func SetMode(value string)

SetMode 按输入的字符串设置当前的模式(DebugMode,ReleaseMode,TestMode).

Types

type Accounts

type Accounts map[string]string

Accounts 为授权登录的user/pass列表定义key/value

type Boarder

type Boarder struct {
	Handlers HandlersChain
	// contains filtered or unexported fields
}

Boarder 在内部用于配置路由器,Boarder前缀和handlers数组(中间件)相关联.

func (*Boarder) Any

func (boarder *Boarder) Any(relativePath string, handlers ...HandlerFunc) IRoutes

Any 注册与所有HTTP方法匹配的路由. GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.

func (*Boarder) BasePath

func (boarder *Boarder) BasePath() string

BasePath 返回跳板的基础路径(相同前缀).

func (*Boarder) Board

func (boarder *Boarder) Board(relativePath string, handlers ...HandlerFunc) *Boarder

Board 创建新的跳板. 您应该添加具有公共中间件或相同路径前缀的所有路由.

func (*Boarder) DELETE

func (boarder *Boarder) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes

DELETE 是router.Handle("DELETE", path, handle)的语法糖.

func (*Boarder) GET

func (boarder *Boarder) GET(relativePath string, handlers ...HandlerFunc) IRoutes

GET 是router.Handle("GET", path, handle)的语法糖.

func (*Boarder) HEAD

func (boarder *Boarder) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes

HEAD 是router.Handle("HEAD", path, handle)的语法糖.

func (*Boarder) Handle

func (boarder *Boarder) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes

Handle 使用给定的路径和方法注册新的handle和中间件.(批量加载) 最后handle才是真正的处理程序,其他应该是公共中间件.允许使用不常用|非标准化|自定义的方法(如,与代理的内部通信)

func (*Boarder) OPTIONS

func (boarder *Boarder) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes

OPTIONS 是router.Handle("OPTIONS", path, handle)的语法糖.

func (*Boarder) PATCH

func (boarder *Boarder) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes

PATCH 是router.Handle("PATCH", path, handle)的语法糖.

func (*Boarder) POST

func (boarder *Boarder) POST(relativePath string, handlers ...HandlerFunc) IRoutes

POST router.Handle("POST", path, handle)的语法糖.

func (*Boarder) PUT

func (boarder *Boarder) PUT(relativePath string, handlers ...HandlerFunc) IRoutes

PUT 是router.Handle("PUT", path, handle)的语法糖.

func (*Boarder) Static

func (boarder *Boarder) Static(relativePath, root string) IRoutes

Static 静态文件夹路由注册. 内部的 http.FileServer 被使用,因此 http.NotFound 不是用来替代路由的 NotFound handler.

func (*Boarder) StaticFS

func (boarder *Boarder) StaticFS(relativePath string, fs http.FileSystem) IRoutes

StaticFS 同Static(),但它有自定义的http.FileSystem替代.

func (*Boarder) StaticFile

func (boarder *Boarder) StaticFile(relativePath, filepath string) IRoutes

StaticFile 静态文件路由注册(单). router.StaticFile("favicon.ico", "./resources/favicon.ico")

func (*Boarder) Use

func (boarder *Boarder) Use(middleware ...HandlerFunc) IRoutes

Use 给跳板添加中间件.

type Centre

type Centre struct {
	Boarder
	AppCentre              bool  //
	RedirectTrailingSlash  bool  // 反斜杠结尾路径自动重定向
	HandleMethodNotAllowed bool  // 请求体内部转递
	ForwardedByClientIP    bool  // 转发连接IP
	UseRawPath             bool  // url.RawPath查找参数
	UnescapePathValues     bool  // 不转义,使用url.Path
	RemoveExtraSlash       bool  // 是否删除额外的反斜杠
	MaxMultipartMemory     int64 // 表单上传最大限制

	HTMLRender render.HTMLRender // 返回渲染模板的接口
	FuncMap    template.FuncMap  // 名称到函数的映射
	// contains filtered or unexported fields
}

Centre 中枢

func Default

func Default() *Centre

Default 返回已附加记录器和恢复中间件的Centre实例

func New

func New() *Centre

New 返回未附加任何中间件的Centre实例

func (*Centre) Delims

func (centre *Centre) Delims(left, right string) *Centre

Delims 设置模板变量的左右分隔符并返回实例

func (*Centre) HandleContext

func (centre *Centre) HandleContext(c *Context)

HandleContext 重新输入已重写的上下文. 这可以通过将 c.Request.URL.Path 设置为新目标来完成. Disclaimer: You can loop yourself to death with this, use wisely.

func (*Centre) LoadHTMLFiles

func (centre *Centre) LoadHTMLFiles(files ...string)

LoadHTMLFiles 加载HTML文件片段并将结果与HTML呈现器关联

func (*Centre) LoadHTMLGlob

func (centre *Centre) LoadHTMLGlob(pattern string)

LoadHTMLGlob 加载由glob模式标识的HTML文件,并将结果与HTML呈现器关联

func (*Centre) NoMethod

func (centre *Centre) NoMethod(handlers ...HandlerFunc)

NoMethod 为NoMethod添加handlers. 默认返回405代码.

func (*Centre) NoRoute

func (centre *Centre) NoRoute(handlers ...HandlerFunc)

NoRoute 为NoRoute添加handlers. 默认返回404代码.

func (*Centre) Routes

func (centre *Centre) Routes() (routes Routes)

Routes Routes

func (*Centre) Run

func (centre *Centre) Run(addr ...string) (err error)

Run 监听并服务请求. http.ListenAndServe(addr, router) 的快捷实现 Note: 除非发生错误,否则此方法将一直阻止调用 goroutine

func (*Centre) RunFd

func (centre *Centre) RunFd(fd int) (err error)

RunFd 监听并服务HTTP请求.通过指定的文件描述符. Note: 除非发生错误,否则此方法将一直阻止调用 goroutine

func (*Centre) RunListener

func (centre *Centre) RunListener(listener net.Listener) (err error)

RunListener 监听并服务HTTP请求.通过指定的文件描述符. 通过指定的net.Listener

func (*Centre) RunTLS

func (centre *Centre) RunTLS(addr, certFile, keyFile string) (err error)

RunTLS 监听并服务HTTPS (secure)请求. http.ListenAndServeTLS(addr, certFile, keyFile, router) 的快捷实现 Note: 除非发生错误,否则此方法将一直阻止调用 goroutine

func (*Centre) RunUnix

func (centre *Centre) RunUnix(file string) (err error)

RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests 通过指定的unix socket (ie. 文件). Note: 除非发生错误,否则此方法将一直阻止调用 goroutine

func (*Centre) ServeHTTP

func (centre *Centre) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP 遵从 http.Handler 接口.

func (*Centre) SetFuncMap

func (centre *Centre) SetFuncMap(funcMap template.FuncMap)

SetFuncMap 设置 FuncMap 的值 template.FuncMap.

func (*Centre) SetHTMLTemplate

func (centre *Centre) SetHTMLTemplate(templ *template.Template)

SetHTMLTemplate 将模板与HTML呈现器关联.

func (*Centre) Use

func (centre *Centre) Use(middleware ...HandlerFunc) IRoutes

Use 将全局中间件连接到路由器. ie.通过 Use() 附加的中间件将包含在每个请求的处理程序链中. 甚至是 404, 405, 静态文件... 这是日志记录器和错误管理中间件的好位置

type Context

type Context struct {
	Writer  ResponseWriter // ResonseWriter接口
	Request *http.Request  // 肯定要存储来自客户端的原始请求
	Params  Params         // URL路径参数,eg:/:name/

	Keys     map[string]interface{} // 专门用于上下文的键/值对
	Errors   errorMsgs              // Errors 错误列表.
	Accepted []string               // 定义了允许的格式被用于内容协商(content)
	// contains filtered or unexported fields
}

Context 上下文管理,web核心,它可以在中间件间传递变量.

func (*Context) Abort

func (c *Context) Abort()

Abort 使链不会执行下一个,但仍会执行调用本方法的handler

func (*Context) AbortWithError

func (c *Context) AbortWithError(code int, err error) *Error

AbortWithError 调用AbortWithStatus()和Error()方法.

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(code int)

AbortWithStatus 调用Abort()方法,并写入响应体状态码. 例如,身份验证失败返回401

func (*Context) AbortWithStatusJSON

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

AbortWithStatusJSON 调用Abort()方法,并调用JSON方法.

func (*Context) AsciiJSON

func (c *Context) AsciiJSON(code int, obj interface{})

AsciiJSON 将给定的结构序列化为JSON并使用ASCII格式写入.(随手设置了Content-Type).

func (*Context) Bind

func (c *Context) Bind(obj interface{}) error

Bind 根据不同的Content-Type自动选择绑定,没有可以兼容的绑定将返回错误. 如果输入无效将响应状态码400并设置Content-Type header 为"text/plain"

func (*Context) BindHeader

func (c *Context) BindHeader(obj interface{}) error

BindHeader c.MustBindWith(obj, binding.Header)的语法糖.

func (*Context) BindJSON

func (c *Context) BindJSON(obj interface{}) error

BindJSON c.MustBindWith(obj, binding.JSON)的语法糖.

func (*Context) BindQuery

func (c *Context) BindQuery(obj interface{}) error

BindQuery c.MustBindWith(obj, binding.Query)的语法糖.

func (*Context) BindUri

func (c *Context) BindUri(obj interface{}) error

BindUri 使用 binding.Uri绑定传递的struct指针.错误返回http400.

func (*Context) BindXML

func (c *Context) BindXML(obj interface{}) error

BindXML c.MustBindWith(obj, binding.BindXML)的语法糖.

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP 实现一个尽力返回真实客户端IP的算法, 分析X-Real-IP 和 X-Forwarded-For以便正确处理反向代理,如: nginx|haproxy. Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.

func (*Context) ContentType

func (c *Context) ContentType() string

ContentType 返回请求header的Content-Type.

func (*Context) Cookie

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

Cookie 返回请求中名为name的cookies(未转义的). 如果有多个同名 cookies 则只返回一个.

func (*Context) Copy

func (c *Context) Copy() *Context

Copy 复制可在请求范围外安全使用的副本.必须将context传递给goroutine时必须使用该方法.

func (*Context) Data

func (c *Context) Data(code int, contentType string, data []byte)

Data writes 将Data写入到body流并更新响应状态.

func (*Context) DataFromReader

func (c *Context) DataFromReader(code int, contentLength int64, contentType string, reader io.Reader, extraHeaders map[string]string)

DataFromReader 使用指定的读取器写入body流并更新响应状态.

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

Deadline 恒返回 无截止日期 (ok==false), 也许你应该想调用 Request.Context().Deadline() ?

func (*Context) DefaultPostForm

func (c *Context) DefaultPostForm(key, defaultValue string) string

DefaultPostForm 如上,但是为空时返回指定的默认值.

func (*Context) DefaultQuery

func (c *Context) DefaultQuery(key, defaultValue string) string

DefaultQuery 返回URL中的值(如果存在)."/path?id=1&name=Manu" 不存在,它将返回指定的defaultValue字符串.

c.DefaultQuery("name", "unknown") == "Manu"
c.DefaultQuery("id", "none") == "none"

func (*Context) Done

func (c *Context) Done() <-chan struct{}

Done 恒返回nil(chan将永远等待) 如果你想在连接关闭时中止,应该使用 Request.Context().Done().

func (*Context) Err

func (c *Context) Err() error

Err 恒返回nil,可以用 Request.Context().Err() 替代.

func (*Context) Error

func (c *Context) Error(err error) *Error

* 错误管理 * Error 附加错误到当前Context,并推送到错误列表. 建议在请求解析过程中为每个错误都调用该方法. 可以用一个中间件收集所有错误,并推送到数据库中\打印日志\附加到HTTP响应体中. 如果错误为空将panic.

func (*Context) File

func (c *Context) File(filepath string)

File 以有效的方式将指定的文件写入body流.

func (*Context) FileAttachment

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

FileAttachment 以有效的方式将指定的文件写入body流 在客户端,文件通常是用给定的文件名下载的

func (*Context) FileFromFS

func (c *Context) FileFromFS(filepath string, fs http.FileSystem)

FileFromFS 从 http.FileSystem 将指定的文件写入body流.

func (*Context) FormFile

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

FormFile 按键返回第一个文件.

func (*Context) FullPath

func (c *Context) FullPath() string

FullPath 返回所匹配路由的完整路径.未匹配返回”.

router.GET("/user/:id", func(c *gin.Context) {
    c.FullPath() == "/user/:id" // true
})

func (*Context) Get

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

Get 返回给定的值,和true.空返回(nil, false)

func (*Context) GetBool

func (c *Context) GetBool(key string) (b bool)

GetBool 返回boolean类型的给定值.

func (*Context) GetDuration

func (c *Context) GetDuration(key string) (d time.Duration)

GetDuration 返回Duration(持续时间)类型的给定值.

func (*Context) GetFloat64

func (c *Context) GetFloat64(key string) (f64 float64)

GetFloat64 返回float64类型的给定值.

func (*Context) GetHeader

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

GetHeader 从请求的headers里返回值.

func (*Context) GetInt

func (c *Context) GetInt(key string) (i int)

GetInt 返回int类型的给定值.

func (*Context) GetInt64

func (c *Context) GetInt64(key string) (i64 int64)

GetInt64 返回int64类型的给定值.

func (*Context) GetPostForm

func (c *Context) GetPostForm(key string) (string, bool)

GetPostForm 如PostForm(key).从POST urlencoded返回(string, bool) 即使不存在也会返回("", false).存在键为空也会返回("", true)

func (*Context) GetPostFormArray

func (c *Context) GetPostFormArray(key string) ([]string, bool)

GetPostFormArray 返回([]string, bool),len>0为真.

func (*Context) GetPostFormMap

func (c *Context) GetPostFormMap(key string) (map[string]string, bool)

GetPostFormMap 返回([]string, bool),len>0为真.

func (*Context) GetQuery

func (c *Context) GetQuery(key string) (string, bool)

GetQuery 返回URL中的值."/path?lastname=" 存在(即使值是空的)返回(value, true),否则返回("", false).

("", false) == c.GetQuery("id")
("", true) == c.GetQuery("lastname")

func (*Context) GetQueryArray

func (c *Context) GetQueryArray(key string) ([]string, bool)

GetQueryArray 返回(values, true),不存在则返回([]string{}, false).

func (*Context) GetQueryMap

func (c *Context) GetQueryMap(key string) (map[string]string, bool)

GetQueryMap 返回指定键映射的map[string]string和bool(存在为true,包含空).

func (*Context) GetRawData

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

GetRawData 返回流数据.

func (*Context) GetString

func (c *Context) GetString(key string) (s string)

GetString 返回字符串类型的给定值.

func (*Context) GetStringMap

func (c *Context) GetStringMap(key string) (sm map[string]interface{})

GetStringMap 返回map[string]interface{}类型的给定值.

func (*Context) GetStringMapString

func (c *Context) GetStringMapString(key string) (sms map[string]string)

GetStringMapString 返回map[string]string类型的给定值.

func (*Context) GetStringMapStringSlice

func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)

GetStringMapStringSlice 返回map[string][]string类型的给定值.

func (*Context) GetStringSlice

func (c *Context) GetStringSlice(key string) (ss []string)

GetStringSlice 返回字符串数组类型的给定值.

func (*Context) GetTime

func (c *Context) GetTime(key string) (t time.Time)

GetTime 返回time类型的给定值.

func (*Context) HTML

func (c *Context) HTML(code int, name string, obj interface{})

HTML 渲染模版(指定模板文件,随手设置了响应状态码和Content-Type).

func (*Context) Handler

func (c *Context) Handler() HandlerFunc

Handler 返回主handler.

func (*Context) HandlerName

func (c *Context) HandlerName() string

HandlerName 返回主handler的名称.调用hanlerschain中的last,并返回它的名称

func (*Context) HandlerNames

func (c *Context) HandlerNames() []string

HandlerNames 降序返回已注册handlers的列表,遵循HandlerName()的语义

func (*Context) Header

func (c *Context) Header(key, value string)

Header 是c.Writer.Header().Set(key, value)的语法糖.写入header. 如果值为空,将删除该header,即`c.Writer.Header().Del(key)`

func (*Context) IndentedJSON

func (c *Context) IndentedJSON(code int, obj interface{})

IndentedJSON 将给定的结构序列化为JSON (缩进+换行)并写入. (随手设置了Content-Type). 警告: 该方法虽然可读性高,但会比JSON()消耗更多资源,所以建议只在开发中使用.

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted 当流程被中止,返回true.

func (*Context) IsWebsocket

func (c *Context) IsWebsocket() bool

IsWebsocket 如果请求headers显示客户端正常启动websocket握手,返回true

func (*Context) JSON

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

JSON 将给定的结构序列化为JSON并写入(随手设置了Content-Type). 在开发模式中,JSON 呈现为 (缩进+换行)

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm 返回解析的multipart form(包含文件上传).

func (*Context) MustBindWith

func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error

MustBindWith 使用binding engine绑定传递的struct指针.错误返回http400.

func (*Context) MustGet

func (c *Context) MustGet(key string) interface{}

MustGet 如果值存在就返回,否则抛出异常

func (*Context) Negotiate

func (c *Context) Negotiate(code int, config Negotiate)

Negotiate 调用不同的渲染器(可调用的).

func (*Context) NegotiateFormat

func (c *Context) NegotiateFormat(offered ...string) string

NegotiateFormat 返回可用的Accept格式.

func (*Context) Next

func (c *Context) Next()

Next 在中间件内被调用.按index来按序调用链内的handlers

func (*Context) Param

func (c *Context) Param(key string) string

Param 根据键返回URL里的指定值."/user/:id",c.Param("id")返回具体值

func (*Context) PostForm

func (c *Context) PostForm(key string) string

PostForm 返回POSTurlencoded form或multipart form指定键的值,或返回""

func (*Context) PostFormArray

func (c *Context) PostFormArray(key string) []string

PostFormArray 根据表单key返回字符串数组.

func (*Context) PostFormMap

func (c *Context) PostFormMap(key string) map[string]string

PostFormMap 按key返回map[string]string.

func (*Context) PureJSON

func (c *Context) PureJSON(code int, obj interface{})

PureJSON 将给定的结构序列化为JSON并写入(不使用unicode替换特殊字符).

func (*Context) Query

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

Query 返回URL中的值."/path?id=1&name=Manu",c.Query("id")=="1234" 相当于 `c.Request.URL.Query().Get(key)`

func (*Context) QueryArray

func (c *Context) QueryArray(key string) []string

QueryArray 返回指定键的[]string.长度取决于包含指定键的参数数量.

func (*Context) QueryMap

func (c *Context) QueryMap(key string) map[string]string

QueryMap returns a map for a given query key.

func (*Context) Redirect

func (c *Context) Redirect(code int, location string)

Redirect 返回location的HTTP重定向.

func (*Context) Render

func (c *Context) Render(code int, r render.Render)

Render 写入响应体headers和调用 render.Render 渲染数据.

func (*Context) SSEvent

func (c *Context) SSEvent(name string, message interface{})

SSEvent 将服务器发送的事件写入body流.

func (*Context) SaveUploadedFile

func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error

SaveUploadedFile 上传表单文件到指定的dst.

func (*Context) Set

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

Set 专用于在context中存储新键值对.如果没有使用过 c.Keys ,将初始化它.

func (*Context) SetAccepted

func (c *Context) SetAccepted(formats ...string)

SetAccepted 设置 Accept header data.

func (*Context) SetCookie

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

SetCookie 将Set-Cookie header 添加到ResponseWriter的headers中. 提供的cookie必须是有效的(无效可能会被静默丢弃).

func (*Context) SetSameSite

func (c *Context) SetSameSite(samesite http.SameSite)

SetSameSite 同 cookie

func (*Context) ShouldBind

func (c *Context) ShouldBind(obj interface{}) error

ShouldBind 根据不同的Content-Type自动选择绑定,没有可以兼容的绑定将中止.

func (*Context) ShouldBindBodyWith

func (c *Context) ShouldBindBodyWith(obj interface{}, bb binding.BindingBody) (err error)

ShouldBindBodyWith 将请求体存储在context,并可以在再次调用时使用. 值得注意的是,此函数在绑定前读取,如果只需读取一次,用它可以获得更好的性能体验.

func (*Context) ShouldBindHeader

func (c *Context) ShouldBindHeader(obj interface{}) error

ShouldBindHeader c.ShouldBindWith(obj, binding.Header)的语法糖.

func (*Context) ShouldBindJSON

func (c *Context) ShouldBindJSON(obj interface{}) error

ShouldBindJSON c.ShouldBindWith(obj, binding.JSON)的语法糖.

func (*Context) ShouldBindQuery

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

ShouldBindQuery c.ShouldBindWith(obj, binding.Query)的语法糖.

func (*Context) ShouldBindUri

func (c *Context) ShouldBindUri(obj interface{}) error

ShouldBindUri 使用 binding.Uri 绑定传递的struct指针.

func (*Context) ShouldBindWith

func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error

ShouldBindWith 使用 binding engine 绑定传递的struct指针 .

func (*Context) ShouldBindXML

func (c *Context) ShouldBindXML(obj interface{}) error

ShouldBindXML c.ShouldBindWith(obj, binding.XML)的语法糖.

func (*Context) Status

func (c *Context) Status(code int)

Status 设置HTTP响应代码.

func (*Context) Stream

func (c *Context) Stream(step func(w io.Writer) bool) bool

Stream 发送流式响应并返回布尔值,指示"是否在流中间断开客户端连接"

func (*Context) String

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

String 将给定字符串写入响应正文.

func (*Context) Value

func (c *Context) Value(key interface{}) interface{}

Value 返回与键关联的值,如果没有值与键关联,则返回nil. 使用相同的键连续调用值将返回相同的结果.

func (*Context) XML

func (c *Context) XML(code int, obj interface{})

XML 将给定的结构序列化为XML并写入response body.(随手设置了Content-Type)

type Data

type Data map[string]interface{}

Data map[string]interface{}的快捷方式

func Err added in v1.0.2

func Err(code int, msg string, jsonObj interface{}) Data

Err Data的另一种封装

func (Data) MarshalXML

func (d Data) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML 允许类型D用户xml.Marshal.

type Error

type Error struct {
	Err  error
	Type ErrorType
	Meta interface{}
}

Error 错误的规范.

func (Error) Error

func (msg Error) Error() string

Error 实现 error 接口.

func (*Error) IsType

func (msg *Error) IsType(flags ErrorType) bool

IsType 判断一个错误.

func (*Error) JSON

func (msg *Error) JSON() interface{}

JSON 创建格式正确的JSON

func (*Error) MarshalJSON

func (msg *Error) MarshalJSON() ([]byte, error)

MarshalJSON 实现 json.Marshaller 接口.

func (*Error) SetMeta

func (msg *Error) SetMeta(data interface{}) *Error

SetMeta 设置错误的 meta 数据.

func (*Error) SetType

func (msg *Error) SetType(flags ErrorType) *Error

SetType 设置错误的类型.

type ErrorType

type ErrorType uint64

ErrorType 无符号64位错误代码.

const (
	// ErrorTypeBind 在Context.Bind()失败时使用.
	ErrorTypeBind ErrorType = 1 << 63 //
	// ErrorTypeRender 在Context.Render()失败时使用.
	ErrorTypeRender ErrorType = 1 << 62 //
	// ErrorTypePrivate 表示私有错误.
	ErrorTypePrivate ErrorType = 1 << 0 //
	// ErrorTypePublic 表示公共错误.
	ErrorTypePublic ErrorType = 1 << 1 //
	// ErrorTypeAny 表示其他错误.
	ErrorTypeAny ErrorType = 1<<64 - 1 //
	// ErrorTypeNu 表示其他错误.
	ErrorTypeNu = 2 //
)

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc 定义中间件的handler为返回值.

func BasicAuth

func BasicAuth(accounts Accounts) HandlerFunc

BasicAuth 返回一个基本的HTTP授权中间件. 它接收 map[string]string作为参数 the key is the user name and the value is the password.

func BasicAuthForRealm

func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc

BasicAuthForRealm 返回一个基本的HTTP授权中间件.map[string]string作为参数. 其中 密钥是用户名,值是密码,以及域的名称. 如果域为空,则默认使用"需要授权" (see http://tools.ietf.org/html/rfc2617#section-1.2)

func Bind

func Bind(val interface{}) HandlerFunc

Bind 用于封装给定接口对象的帮助函数,并返回中间件 .

func Logger

func Logger() HandlerFunc

Logger 将logger方法转为可用的中间件(上下文)

func LoggerWithConfig

func LoggerWithConfig(conf LoggerConfig) HandlerFunc

LoggerWithConfig 使用config实例化记录器中间件.

func LoggerWithFormatter

func LoggerWithFormatter(f LogFormatter) HandlerFunc

LoggerWithFormatter 使用指定的日志格式函数实例化记录器中间件.

func LoggerWithWriter

func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc

LoggerWithWriter 使用指定的编写器缓冲区实例化记录器中间件.

func Recovery

func Recovery() HandlerFunc

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.

func RecoveryWithWriter

func RecoveryWithWriter(out io.Writer) HandlerFunc

RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.

func WrapF

func WrapF(f http.HandlerFunc) HandlerFunc

WrapF 用于封装http.HandlerFunc的帮助函数并返回一个中间件.

func WrapH

func WrapH(h http.Handler) HandlerFunc

WrapH 用于封装http.HandlerFunc的帮助函数并返回一个中间件.

type HandlersChain

type HandlersChain []HandlerFunc

HandlersChain 定义 HandlerFunc 数组.

func (HandlersChain) Last

func (c HandlersChain) Last() HandlerFunc

Last 返回Chain里的最后一个Handler. 即. 最后一个Handler才是路由的主Handler.

type IBoarder

type IBoarder interface {
	IRoutes
	Board(string, ...HandlerFunc) *Boarder
}

IBoarder 定义所有路由器句柄接口,包括单路由器和跳板.

type IRoutes

type IRoutes interface {
	Use(...HandlerFunc) IRoutes

	Handle(string, string, ...HandlerFunc) IRoutes
	Any(string, ...HandlerFunc) IRoutes
	GET(string, ...HandlerFunc) IRoutes
	POST(string, ...HandlerFunc) IRoutes
	DELETE(string, ...HandlerFunc) IRoutes
	PATCH(string, ...HandlerFunc) IRoutes
	PUT(string, ...HandlerFunc) IRoutes
	OPTIONS(string, ...HandlerFunc) IRoutes
	HEAD(string, ...HandlerFunc) IRoutes

	StaticFile(string, string) IRoutes
	Static(string, string) IRoutes
	StaticFS(string, http.FileSystem) IRoutes
}

IRoutes 定义所有路由器句柄接口.

type LogFormatter

type LogFormatter func(params LogFormatterParams) string

LogFormatter 给定格式器函数的签名传递给LoggerWithFormatter.

type LogFormatterParams

type LogFormatterParams struct {
	Request      *http.Request // web 请求内容
	TimeStamp    time.Time     // 服务器返回响应后的时间
	StatusCode   int           // HTTP响应状态码
	Latency      time.Duration // 处理请求耗时
	ClientIP     string        // 等于ClientIP方法
	Method       string        // 来自客户端请求的方法
	Path         string        // 来自客户端请求的路径
	ErrorMessage string        // 处理请求时记录错误信息

	BodySize int                    // 响应体正文大小
	Keys     map[string]interface{} // 请求的上下文中设置的键
	// contains filtered or unexported fields
}

LogFormatterParams 格式器在进行日志记录时需要的参数.

func (*LogFormatterParams) IsOutputColor

func (p *LogFormatterParams) IsOutputColor() bool

IsOutputColor 是否可以将颜色输出到日志.

func (*LogFormatterParams) MethodColor

func (p *LogFormatterParams) MethodColor() string

MethodColor 给状态码设置适当颜色.(输出日志到终端)

func (*LogFormatterParams) ResetColor

func (p *LogFormatterParams) ResetColor() string

ResetColor 重置所有转义属性.

func (*LogFormatterParams) StatusCodeColor

func (p *LogFormatterParams) StatusCodeColor() string

StatusCodeColor 给状态码设置适当颜色.(ANSI,输出日志到终端)

type LoggerConfig

type LoggerConfig struct {
	Formatter LogFormatter // 可选格式器.有默认值
	Output    io.Writer    // 可选写入器.有默认值
	SkipPaths []string     // 可选.跳过写入的url路径(数组)
}

LoggerConfig 定义日志中间件配置.

type Negotiate

type Negotiate struct {
	Offered  []string
	HTMLName string
	HTMLData interface{}
	JSONData interface{}
	XMLData  interface{}
	Data     interface{}
}

Negotiate 包含所有negotiations数据.

type Param

type Param struct {
	Key   string
	Value string
}

Param 单个URL参数,由键和值组成.

type Params

type Params []Param

Params Param切片,由路由返回.(支持索引)

func (Params) ByName

func (ps Params) ByName(name string) (va string)

ByName 返回指定键名匹配到的首个值.不存在则返回nil

func (Params) Get

func (ps Params) Get(name string) (string, bool)

Get 返回指定键名匹配到的首个值.不存在则返回nil

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher
	http.CloseNotifier
	Status() int                     // 返回当前请求的HTTP响应状态代码
	Size() int                       // 返回已写入响应http正文的字节数
	WriteString(string) (int, error) // 将字符串写入响应正文
	Written() bool                   // 是否已已写入响应正文[]
	WriteHeaderNow()                 // 强制写入状态代码和headers
	Pusher() http.Pusher             // 得到http.Pusher用于服务器推送
}

ResponseWriter ...

type Route

type Route struct {
	Method      string
	Path        string
	Handler     string
	HandlerFunc HandlerFunc
}

Route 表示包含方法和路径及其处理程序的请求路由的规范.

type Routes

type Routes []Route

Routes defines a RouteInfo array.

Directories

Path Synopsis
internal
sse

Jump to

Keyboard shortcuts

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