Documentation ¶
Overview ¶
Package web 为社区优秀的 Web 服务器提供一个抽象层,使得底层可以灵活切换。
Index ¶
- Constants
- Variables
- func FuncFilter(f func(ctx Context, chain FilterChain)) *funcFilter
- func GetMethod(method uint32) (r []string)
- func InvokeHandler(ctx Context, fn Handler, filters []Filter)
- func NewRouter() *router
- func RegisterSwaggerHandler(handler SwaggerHandler)
- func StartRecord(ctx Context)
- func StartReplay(ctx Context)
- func StopRecord(ctx Context)
- func StopReplay(ctx Context)
- func ToPathStyle(path string, style PathStyleEnum) (string, string)
- func URLPatterns(filters []Filter) (*urlPatterns, error)
- func WithFileLine(err error, skip int) error
- type AbstractContainer
- func (c *AbstractContainer) AddFilter(filter ...Filter)
- func (r *AbstractContainer) AddMapper(m *Mapper)
- func (c *AbstractContainer) Address() string
- func (c *AbstractContainer) Config() ContainerConfig
- func (r *AbstractContainer) DeleteBinding(path string, fn interface{}) *Mapper
- func (r *AbstractContainer) DeleteMapping(path string, fn HandlerFunc) *Mapper
- func (r *AbstractContainer) GetBinding(path string, fn interface{}) *Mapper
- func (c *AbstractContainer) GetFilters() []Filter
- func (c *AbstractContainer) GetLoggerFilter() Filter
- func (r *AbstractContainer) GetMapping(path string, fn HandlerFunc) *Mapper
- func (r *AbstractContainer) HandleDelete(path string, h Handler) *Mapper
- func (r *AbstractContainer) HandleGet(path string, h Handler) *Mapper
- func (r *AbstractContainer) HandlePost(path string, h Handler) *Mapper
- func (r *AbstractContainer) HandlePut(path string, h Handler) *Mapper
- func (r *AbstractContainer) HandleRequest(method uint32, path string, h Handler) *Mapper
- func (r *AbstractContainer) Mappers() []*Mapper
- func (r *AbstractContainer) PostBinding(path string, fn interface{}) *Mapper
- func (r *AbstractContainer) PostMapping(path string, fn HandlerFunc) *Mapper
- func (r *AbstractContainer) PutBinding(path string, fn interface{}) *Mapper
- func (r *AbstractContainer) PutMapping(path string, fn HandlerFunc) *Mapper
- func (r *AbstractContainer) RequestBinding(method uint32, path string, fn interface{}) *Mapper
- func (r *AbstractContainer) RequestMapping(method uint32, path string, fn HandlerFunc) *Mapper
- func (c *AbstractContainer) SetLoggerFilter(filter Filter)
- func (c *AbstractContainer) Start() error
- func (c *AbstractContainer) Stop(ctx context.Context) error
- func (c *AbstractContainer) Swagger(swagger Swagger)
- type BufferedResponseWriter
- type Container
- type ContainerConfig
- type Context
- type DefaultFilterChain
- type ErrorCode
- type Filter
- type FilterChain
- type Handler
- type HandlerFunc
- type HttpError
- type Mapper
- type Operation
- type PathStyleEnum
- type ResponseWriter
- type Router
- type RpcError
- type RpcResult
- type RpcSuccess
- type Swagger
- type SwaggerHandler
Constants ¶
const ( HeaderContentDisposition = "Content-Disposition" HeaderContentType = "Content-Type" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" CharsetUTF8 = "charset=UTF-8" MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + CharsetUTF8 MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + CharsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + CharsetUTF8 MIMETextXML = "text/xml" MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + CharsetUTF8 MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEApplicationProtobuf = "application/protobuf" MIMEApplicationMsgpack = "application/msgpack" MIMETextHTML = "text/html" MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + CharsetUTF8 MIMETextPlain = "text/plain" MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + CharsetUTF8 MIMEMultipartForm = "multipart/form-data" MIMEOctetStream = "application/octet-stream" MIMEJsonAPI = "application/vnd.api+json" MIMEJsonStream = "application/x-json-stream" MIMEImagePng = "image/png" MIMEImageJpeg = "image/jpeg" MIMEImageGif = "image/gif" )
const ( MethodGet = 0x0001 // "GET" MethodHead = 0x0002 // "HEAD" MethodPost = 0x0004 // "POST" MethodPut = 0x0008 // "PUT" MethodPatch = 0x0010 // "PATCH" MethodDelete = 0x0020 // "DELETE" MethodConnect = 0x0040 // "CONNECT" MethodOptions = 0x0080 // "OPTIONS" MethodTrace = 0x0100 // "TRACE" MethodAny = 0xffff MethodGetPost = MethodGet | MethodPost )
const ( EchoPathStyle = PathStyleEnum(0) GinPathStyle = PathStyleEnum(1) JavaPathStyle = PathStyleEnum(2) )
const ContextKey = "@WebCtx"
ContextKey Context 和 NativeContext 相互转换的 Key
const DefaultWildCardName = "@_@"
DefaultWildCardName 默认通配符的名称
const ReplaySessionID = "REPLAY-SESSION-ID"
ReplaySessionID 流量回放模式下传递会话 ID 使用的 Header 。
Variables ¶
var ( ERROR = NewRpcError(-1, "ERROR") SUCCESS = NewRpcSuccess(200, "SUCCESS") DEFAULT = NewErrorCode(math.MaxInt32, "DEFAULT") )
var ErrorHandler = func(ctx Context, err *HttpError) { defer func() { if r := recover(); r != nil { log.Ctx(ctx.Context()).Error(r) } }() if err.Internal == nil { ctx.Status(err.Code) ctx.String(err.Message) } else { ctx.JSON(err.Internal) } }
ErrorHandler 用户自定义错误处理函数
var RpcInvoke = func(ctx Context, fn func(Context) interface{}) {
ctx.JSON(fn(ctx))
}
RpcInvoke 可自定义的 rpc 执行函数
Functions ¶
func FuncFilter ¶
func FuncFilter(f func(ctx Context, chain FilterChain)) *funcFilter
func InvokeHandler ¶
InvokeHandler 执行 Web 处理函数
func RegisterSwaggerHandler ¶
func RegisterSwaggerHandler(handler SwaggerHandler)
RegisterSwaggerHandler 注册 Swagger 处理器
func ToPathStyle ¶
func ToPathStyle(path string, style PathStyleEnum) (string, string)
ToPathStyle 将 URL 转换为指定风格的表示形式
func URLPatterns ¶
URLPatterns 根据 Filter 的 URL 匹配表达式进行分组。
func WithFileLine ¶
WithFileLine 返回错误发生的文件行号,skip 是相对于当前函数的深度。
Types ¶
type AbstractContainer ¶
type AbstractContainer struct {
// contains filtered or unexported fields
}
AbstractContainer 抽象的 Container 实现
func NewAbstractContainer ¶
func NewAbstractContainer(config ContainerConfig) *AbstractContainer
NewAbstractContainer AbstractContainer 的构造函数
func (*AbstractContainer) AddFilter ¶
func (c *AbstractContainer) AddFilter(filter ...Filter)
AddFilter 添加过滤器
func (*AbstractContainer) AddMapper ¶
func (r *AbstractContainer) AddMapper(m *Mapper)
AddMapper 添加一个 Mapper
func (*AbstractContainer) Config ¶
func (c *AbstractContainer) Config() ContainerConfig
Config 获取 Web 容器配置
func (*AbstractContainer) DeleteBinding ¶
DeleteBinding 注册 DELETE 方法处理函数
func (*AbstractContainer) DeleteMapping ¶
func (r *AbstractContainer) DeleteMapping(path string, fn HandlerFunc) *Mapper
DeleteMapping 注册 DELETE 方法处理函数
func (*AbstractContainer) GetBinding ¶
GetBinding 注册 GET 方法处理函数
func (*AbstractContainer) GetFilters ¶
func (c *AbstractContainer) GetFilters() []Filter
GetFilters 返回过滤器列表
func (*AbstractContainer) GetLoggerFilter ¶
func (c *AbstractContainer) GetLoggerFilter() Filter
GetLoggerFilter 获取 Logger Filter
func (*AbstractContainer) GetMapping ¶
func (r *AbstractContainer) GetMapping(path string, fn HandlerFunc) *Mapper
GetMapping 注册 GET 方法处理函数
func (*AbstractContainer) HandleDelete ¶
HandleDelete 注册 DELETE 方法处理函数
func (*AbstractContainer) HandlePost ¶
HandlePost 注册 POST 方法处理函数
func (*AbstractContainer) HandleRequest ¶
HandleRequest 注册任意 HTTP 方法处理函数
func (*AbstractContainer) PostBinding ¶
PostBinding 注册 POST 方法处理函数
func (*AbstractContainer) PostMapping ¶
func (r *AbstractContainer) PostMapping(path string, fn HandlerFunc) *Mapper
PostMapping 注册 POST 方法处理函数
func (*AbstractContainer) PutBinding ¶
PutBinding 注册 PUT 方法处理函数
func (*AbstractContainer) PutMapping ¶
func (r *AbstractContainer) PutMapping(path string, fn HandlerFunc) *Mapper
PutMapping 注册 PUT 方法处理函数
func (*AbstractContainer) RequestBinding ¶
RequestBinding 注册任意 HTTP 方法处理函数
func (*AbstractContainer) RequestMapping ¶
func (r *AbstractContainer) RequestMapping(method uint32, path string, fn HandlerFunc) *Mapper
RequestMapping 注册任意 HTTP 方法处理函数
func (*AbstractContainer) SetLoggerFilter ¶
func (c *AbstractContainer) SetLoggerFilter(filter Filter)
SetLoggerFilter 设置 Logger Filter
func (*AbstractContainer) Stop ¶
func (c *AbstractContainer) Stop(ctx context.Context) error
Stop 停止 Web 容器
func (*AbstractContainer) Swagger ¶
func (c *AbstractContainer) Swagger(swagger Swagger)
Swagger 设置与容器绑定的 Swagger 对象
type BufferedResponseWriter ¶
type BufferedResponseWriter struct { http.ResponseWriter // contains filtered or unexported fields }
BufferedResponseWriter http.ResponseWriter 的一种增强型实现.
func (*BufferedResponseWriter) Body ¶
func (w *BufferedResponseWriter) Body() string
Body 返回发送给客户端的数据,当前仅支持 MIMEApplicationJSON 格式.
func (*BufferedResponseWriter) Size ¶
func (w *BufferedResponseWriter) Size() int
Size Returns the number of bytes already written into the response http body.
func (*BufferedResponseWriter) Status ¶
func (w *BufferedResponseWriter) Status() int
Status Returns the HTTP response status code of the current request.
func (*BufferedResponseWriter) Write ¶
func (w *BufferedResponseWriter) Write(data []byte) (n int, err error)
func (*BufferedResponseWriter) WriteHeader ¶
func (w *BufferedResponseWriter) WriteHeader(code int)
type Container ¶
type Container interface { Router // Config 获取 Web 容器配置 Config() ContainerConfig // GetFilters 返回过滤器列表 GetFilters() []Filter // AddFilter 添加过滤器 AddFilter(filter ...Filter) // GetLoggerFilter 获取 Logger Filter GetLoggerFilter() Filter // SetLoggerFilter 设置 Logger Filter SetLoggerFilter(filter Filter) // Swagger 设置与容器绑定的 Swagger 对象 Swagger(swagger Swagger) // Start 启动 Web 容器 Start() error // Stop 停止 Web 容器 Stop(ctx context.Context) error }
Container Web 容器
type ContainerConfig ¶
type ContainerConfig struct { IP string // 监听 IP Port int // 监听端口 EnableSSL bool // 使用 SSL KeyFile string // SSL 证书 CertFile string // SSL 秘钥 BasePath string // 根路径 ReadTimeout time.Duration WriteTimeout time.Duration }
ContainerConfig Web 容器配置
type Context ¶
type Context interface { // NativeContext 返回封装的底层上下文对象 NativeContext() interface{} // Request returns `*http.Request`. Request() *http.Request // SetRequest sets `*http.Request`. SetRequest(r *http.Request) // Context 返回 Request 绑定的 context.Context 对象 Context() context.Context // IsTLS returns true if HTTP connection is TLS otherwise false. IsTLS() bool // IsWebSocket returns true if HTTP connection is WebSocket otherwise false. IsWebSocket() bool // Scheme returns the HTTP protocol scheme, `http` or `https`. Scheme() 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. Use X-Forwarded-For before // X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP. ClientIP() string // Path returns the registered path for the handler. Path() string // Handler returns the matched handler by router. Handler() Handler // ContentType returns the Content-Type header of the request. ContentType() string // GetHeader returns value from request headers. GetHeader(key string) string // GetRawData return stream data. GetRawData() ([]byte, error) // PathParam returns path parameter by name. PathParam(name string) string // PathParamNames returns path parameter names. PathParamNames() []string // PathParamValues returns path parameter values. PathParamValues() []string // QueryParam returns the query param for the provided name. QueryParam(name string) string // QueryParams returns the query parameters as `url.Values`. QueryParams() url.Values // QueryString returns the URL query string. QueryString() string // FormValue returns the form field value for the provided name. FormValue(name string) string // FormParams returns the form parameters as `url.Values`. FormParams() (url.Values, error) // FormFile returns the multipart form file for the provided name. FormFile(name string) (*multipart.FileHeader, error) // SaveUploadedFile uploads the form file to specific dst. SaveUploadedFile(file *multipart.FileHeader, dst string) error // MultipartForm returns the multipart form. MultipartForm() (*multipart.Form, error) // Cookie returns the named cookie provided in the request. Cookie(name string) (*http.Cookie, error) // Cookies returns the HTTP cookies sent with the request. Cookies() []*http.Cookie // Bind binds the request body into provided type `i`. The default binder // does it based on Content-Type header. Bind(i interface{}) error // ResponseWriter returns `http.ResponseWriter`. ResponseWriter() ResponseWriter // Status sets the HTTP response code. Status(code int) // Header is a intelligent shortcut for c.Writer.Header().Set(key, value). // It writes a header in the response. // If value == "", this method removes the header `c.Writer.Header().Del(key)` Header(key, value string) // SetCookie adds a `Set-Cookie` header in HTTP response. SetCookie(cookie *http.Cookie) // NoContent sends a response with no body and a status code. Maybe panic. NoContent(code int) // String writes the given string into the response body. Maybe panic. String(format string, values ...interface{}) // HTML sends an HTTP response. Maybe panic. HTML(html string) // HTMLBlob sends an HTTP blob response. Maybe panic. HTMLBlob(b []byte) // JSON sends a JSON response. Maybe panic. JSON(i interface{}) // JSONPretty sends a pretty-print JSON. Maybe panic. JSONPretty(i interface{}, indent string) // JSONBlob sends a JSON blob response. Maybe panic. JSONBlob(b []byte) // JSONP sends a JSONP response. It uses `callback` // to construct the JSONP payload. Maybe panic. JSONP(callback string, i interface{}) // JSONPBlob sends a JSONP blob response. It uses // `callback` to construct the JSONP payload. Maybe panic. JSONPBlob(callback string, b []byte) // XML sends an XML response. Maybe panic. XML(i interface{}) // XMLPretty sends a pretty-print XML. Maybe panic. XMLPretty(i interface{}, indent string) // XMLBlob sends an XML blob response. Maybe panic. XMLBlob(b []byte) // Blob sends a blob response and content type. Maybe panic. Blob(contentType string, b []byte) // File sends a response with the content of the file. Maybe panic. File(file string) // Attachment sends a response as attachment, prompting client to // save the file. Maybe panic. Attachment(file string, name string) // Inline sends a response as inline, opening the file in the browser. Maybe panic. Inline(file string, name string) // Redirect redirects the request to a provided URL with status code. Maybe panic. Redirect(code int, url string) // SSEvent writes a Server-Sent Event into the body stream. Maybe panic. SSEvent(name string, message interface{}) }
Context 封装 *http.Request 和 http.ResponseWriter 对象,简化操作接口。
type DefaultFilterChain ¶
type DefaultFilterChain struct {
// contains filtered or unexported fields
}
DefaultFilterChain 默认的过滤器链条
func NewDefaultFilterChain ¶
func NewDefaultFilterChain(filters []Filter) *DefaultFilterChain
NewDefaultFilterChain DefaultFilterChain 的构造函数
func (*DefaultFilterChain) Next ¶
func (chain *DefaultFilterChain) Next(ctx Context)
type Filter ¶
type Filter interface {
Invoke(ctx Context, chain FilterChain)
}
Filter 过滤器接口,Invoke 通过 chain.Next() 驱动链条向后执行。
type Handler ¶
type Handler interface { // Invoke 响应函数 Invoke(Context) // FileLine 获取用户函数的文件名、行号以及函数名称 FileLine() (file string, line int, fnName string) }
Handler 标准 Web 处理接口
type HttpError ¶
type HttpError struct { Code int // HTTP 错误码 Message string // 自定义错误消息 Internal interface{} // 保存的原始异常 }
HttpError represents an error that occurred while handling a request.
func NewHttpError ¶
NewHttpError creates a new HttpError instance.
func (*HttpError) SetInternal ¶
SetInternal sets error to HTTPError.Internal
type Mapper ¶
type Mapper struct {
// contains filtered or unexported fields
}
Mapper 路由映射器
type Operation ¶
type Operation interface { // Process 完成处理参数绑定等过程 Process() error }
Operation 与路由绑定的 API 描述文档
type PathStyleEnum ¶
type PathStyleEnum int
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter // Status Returns the HTTP response status code of the current request. Status() int // Size Returns the number of bytes already written into the response http body. Size() int // Body 返回发送给客户端的数据,当前仅支持 MIMEApplicationJSON 格式. Body() string }
ResponseWriter Override http.ResponseWriter to supply more method.
type Router ¶
type Router interface { // Mappers 返回映射器列表 Mappers() []*Mapper // AddMapper 添加一个 Mapper AddMapper(m *Mapper) // HandleGet 注册 GET 方法处理函数 HandleGet(path string, h Handler) *Mapper // GetMapping 注册 GET 方法处理函数 GetMapping(path string, fn HandlerFunc) *Mapper // GetBinding 注册 GET 方法处理函数 GetBinding(path string, fn interface{}) *Mapper // HandlePost 注册 POST 方法处理函数 HandlePost(path string, h Handler) *Mapper // PostMapping 注册 POST 方法处理函数 PostMapping(path string, fn HandlerFunc) *Mapper // PostBinding 注册 POST 方法处理函数 PostBinding(path string, fn interface{}) *Mapper // HandlePut 注册 PUT 方法处理函数 HandlePut(path string, h Handler) *Mapper // PutMapping 注册 PUT 方法处理函数 PutMapping(path string, fn HandlerFunc) *Mapper // PutBinding 注册 PUT 方法处理函数 PutBinding(path string, fn interface{}) *Mapper // HandleDelete 注册 DELETE 方法处理函数 HandleDelete(path string, h Handler) *Mapper // DeleteMapping 注册 DELETE 方法处理函数 DeleteMapping(path string, fn HandlerFunc) *Mapper // DeleteBinding 注册 DELETE 方法处理函数 DeleteBinding(path string, fn interface{}) *Mapper // HandleRequest 注册任意 HTTP 方法处理函数 HandleRequest(method uint32, path string, h Handler) *Mapper // RequestMapping 注册任意 HTTP 方法处理函数 RequestMapping(method uint32, path string, fn HandlerFunc) *Mapper // RequestBinding 注册任意 HTTP 方法处理函数 RequestBinding(method uint32, path string, fn interface{}) *Mapper }
Router 路由注册接口
type RpcError ¶
type RpcError ErrorCode
RpcError 定义一个 RPC 异常值
func (RpcError) ErrorWithData ¶
ErrorWithData 绑定一个错误和一个值
func (RpcError) PanicImmediately ¶
PanicImmediately 立即抛出一个异常值
type RpcResult ¶
type RpcResult struct { ErrorCode Err string `json:"err,omitempty"` // 错误源 Data interface{} `json:"data,omitempty"` // 返回值 }
RpcResult 定义 RPC 返回值
type RpcSuccess ¶
type RpcSuccess ErrorCode
RpcSuccess 定义一个 RPC 成功值
func NewRpcSuccess ¶
func NewRpcSuccess(code int32, msg string) RpcSuccess
NewRpcSuccess RpcSuccess 的构造函数
type Swagger ¶
type Swagger interface { // ReadDoc 读取标准格式的描述文档 ReadDoc() string // AddPath 添加与容器绑定的路由节点 AddPath(path string, method string, op Operation) }
Swagger 与容器绑定的 API 描述文档
type SwaggerHandler ¶
SwaggerHandler Swagger 处理器