Documentation ¶
Overview ¶
Package web 为社区优秀的 Web 服务器提供一个抽象层,使得底层可以灵活切换。
Index ¶
- Constants
- Variables
- func Bind(i interface{}, ctx Context) error
- func BindForm(i interface{}, ctx Context) error
- func BindJSON(i interface{}, ctx Context) error
- func BindXML(i interface{}, ctx Context) error
- func FuncFilter(f FilterFunc) *funcFilter
- func GetHTTPRequest(ctx context.Context) *http.Request
- func GetMethod(method uint32) (r []string)
- func NewRouter() *router
- func NewServer(config ServerConfig, handler ServerHandler) *server
- func RegisterBodyBinder(mime string, binder BodyBinder)
- func RegisterScopeBinder(scope BindScope, tag string)
- func RegisterSwaggerHandler(handler SwaggerHandler)
- func ToPathStyle(path string, style PathStyleEnum) (newPath string, wildcard string)
- func URLPatternFilter(f Filter, s ...string) *urlPatternFilter
- func URLPatterns(filters []Filter) (*urlPatterns, error)
- func WithFileLine(err error, skip int) error
- type BaseContext
- func (c *BaseContext) Attachment(file string, name string)
- func (c *BaseContext) Bind(i interface{}) error
- func (c *BaseContext) Blob(contentType string, b []byte)
- func (c *BaseContext) ClientIP() string
- func (c *BaseContext) ContentType() string
- func (c *BaseContext) Context() context.Context
- func (c *BaseContext) Cookie(name string) (*http.Cookie, error)
- func (c *BaseContext) Cookies() []*http.Cookie
- func (c *BaseContext) File(file string)
- func (c *BaseContext) FormFile(name string) (*multipart.FileHeader, error)
- func (c *BaseContext) FormParams() (url.Values, error)
- func (c *BaseContext) FormValue(name string) string
- func (c *BaseContext) Get(key string) interface{}
- func (c *BaseContext) HTML(html string)
- func (c *BaseContext) HTMLBlob(b []byte)
- func (c *BaseContext) Handler() Handler
- func (c *BaseContext) Header(key string) string
- func (c *BaseContext) Inline(file string, name string)
- func (c *BaseContext) IsTLS() bool
- func (c *BaseContext) IsWebSocket() bool
- func (c *BaseContext) JSON(i interface{})
- func (c *BaseContext) JSONBlob(b []byte)
- func (c *BaseContext) JSONP(callback string, i interface{})
- func (c *BaseContext) JSONPBlob(callback string, b []byte)
- func (c *BaseContext) JSONPretty(i interface{}, indent string)
- func (c *BaseContext) MultipartForm() (*multipart.Form, error)
- func (c *BaseContext) NativeContext() interface{}
- func (c *BaseContext) NoContent(code int)
- func (c *BaseContext) Path() string
- func (c *BaseContext) PathParam(name string) string
- func (c *BaseContext) PathParamNames() []string
- func (c *BaseContext) PathParamValues() []string
- func (c *BaseContext) QueryParam(name string) string
- func (c *BaseContext) QueryParams() url.Values
- func (c *BaseContext) QueryString() string
- func (c *BaseContext) Redirect(code int, url string)
- func (c *BaseContext) Request() *http.Request
- func (c *BaseContext) RequestBody() ([]byte, error)
- func (c *BaseContext) Response() Response
- func (c *BaseContext) SSEvent(name string, message interface{})
- func (c *BaseContext) SaveUploadedFile(file *multipart.FileHeader, dst string) error
- func (c *BaseContext) Scheme() string
- func (c *BaseContext) Set(key string, val interface{}) error
- func (c *BaseContext) SetContentType(typ string)
- func (c *BaseContext) SetContext(ctx context.Context)
- func (c *BaseContext) SetCookie(cookie *http.Cookie)
- func (c *BaseContext) SetHeader(key, value string)
- func (c *BaseContext) SetStatus(code int)
- func (c *BaseContext) String(format string, values ...interface{})
- func (c *BaseContext) XML(i interface{})
- func (c *BaseContext) XMLBlob(b []byte)
- func (c *BaseContext) XMLPretty(i interface{}, indent string)
- type BasicAuthConfig
- type BindScope
- type BodyBinder
- type BufferedResponseWriter
- type Context
- type ErrorCode
- type ErrorHandler
- type FileHandler
- type Filter
- func HTTPSNonWWWRedirect(config RedirectConfig) Filter
- func HTTPSRedirect(config RedirectConfig) Filter
- func HTTPSWWWRedirect(config RedirectConfig) Filter
- func HandlerFilter(fn Handler) Filter
- func NewBasicAuthFilter(config BasicAuthConfig) Filter
- func NewGzipFilter(level int) (Filter, error)
- func NewRequestIDFilter(config RequestIDConfig) Filter
- func NonWWWRedirect(config RedirectConfig) Filter
- func WWWRedirect(config RedirectConfig) Filter
- type FilterChain
- type FilterFunc
- type FuncErrorHandler
- type GzipFilter
- type Handler
- type HandlerFunc
- type HttpError
- type Mapper
- type MethodOverrideConfig
- type MethodOverrideGetter
- type NextOperation
- type Operation
- type PathStyleEnum
- type Prefilter
- type RedirectConfig
- type RequestIDConfig
- type Response
- type Router
- type RpcError
- type RpcResult
- type RpcSuccess
- type Server
- type ServerConfig
- type ServerHandler
- type SimpleResponse
- type Swagger
- type SwaggerHandler
Constants ¶
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" HeaderAllow = "Allow" HeaderAuthorization = "Authorization" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderUpgrade = "Upgrade" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXRealIP = "X-Real-IP" HeaderXRequestID = "X-Request-ID" HeaderXCorrelationID = "X-Correlation-ID" HeaderXRequestedWith = "X-Requested-With" HeaderServer = "Server" HeaderOrigin = "Origin" )
const ( HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXXSSProtection = "X-XSS-Protection" HeaderXFrameOptions = "X-Frame-Options" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderXCSRFToken = "X-CSRF-Token" HeaderReferrerPolicy = "Referrer-Policy" )
const ( HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" )
const ( 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 (
AuthUserKey = "::user::"
)
const (
CharsetUTF8 = "charset=UTF-8"
)
const ContextKey = "@@WebCtx@@"
ContextKey Context 和 NativeContext 相互转换的 Key
const DefaultWildcardName = "@_@"
DefaultWildcardName 默认通配符的名称
Variables ¶
var ( ERROR = NewRpcError(-1, "ERROR") SUCCESS = NewRpcSuccess(200, "SUCCESS") DEFAULT = NewErrorCode(math.MaxInt32, "DEFAULT") )
var RPCInvoke = func(ctx Context, fn func(Context) interface{}) {
ctx.JSON(fn(ctx))
}
RPCInvoke 可自定义的 rpc 执行函数。
Functions ¶
func GetHTTPRequest ¶
GetHTTPRequest returns the *http.Request storing in the context.Context.
func NewServer ¶
func NewServer(config ServerConfig, handler ServerHandler) *server
NewServer server 的构造函数
func RegisterBodyBinder ¶ added in v1.1.3
func RegisterBodyBinder(mime string, binder BodyBinder)
func RegisterScopeBinder ¶ added in v1.1.3
func RegisterSwaggerHandler ¶
func RegisterSwaggerHandler(handler SwaggerHandler)
RegisterSwaggerHandler 注册 Swagger 处理器
func ToPathStyle ¶
func ToPathStyle(path string, style PathStyleEnum) (newPath string, wildcard string)
ToPathStyle 将 URL 转换为指定风格的表示形式
func URLPatternFilter ¶
URLPatternFilter 封装带 URLPatterns 信息的过滤器。
func URLPatterns ¶
URLPatterns 根据 Filter 的 URL 匹配表达式进行分组。
func WithFileLine ¶
WithFileLine 返回错误发生的文件行号,skip 是相对于当前函数的深度。
Types ¶
type BaseContext ¶
func NewBaseContext ¶
NewBaseContext 创建 *BaseContext 对象。
func (*BaseContext) Attachment ¶
func (c *BaseContext) Attachment(file string, name string)
Attachment sends a response as attachment
func (*BaseContext) Bind ¶
func (c *BaseContext) Bind(i interface{}) error
Bind binds the request body into provided type `i`.
func (*BaseContext) Blob ¶
func (c *BaseContext) Blob(contentType string, b []byte)
Blob sends a blob response with content type.
func (*BaseContext) ClientIP ¶
func (c *BaseContext) ClientIP() string
ClientIP implements a best effort algorithm to return the real client IP.
func (*BaseContext) ContentType ¶
func (c *BaseContext) ContentType() string
ContentType returns the Content-Type header of the request.
func (*BaseContext) Context ¶
func (c *BaseContext) Context() context.Context
Context 返回 Request 绑定的 context.Context 对象
func (*BaseContext) Cookie ¶
func (c *BaseContext) Cookie(name string) (*http.Cookie, error)
Cookie returns the named cookie provided in the request.
func (*BaseContext) Cookies ¶
func (c *BaseContext) Cookies() []*http.Cookie
Cookies returns the HTTP cookies sent with the request.
func (*BaseContext) File ¶
func (c *BaseContext) File(file string)
File sends a response with the content of the file.
func (*BaseContext) FormFile ¶
func (c *BaseContext) FormFile(name string) (*multipart.FileHeader, error)
FormFile returns the multipart form file for the provided name.
func (*BaseContext) FormParams ¶
func (c *BaseContext) FormParams() (url.Values, error)
FormParams returns the form parameters as `url.Values`.
func (*BaseContext) FormValue ¶
func (c *BaseContext) FormValue(name string) string
FormValue returns the form field value for the provided name.
func (*BaseContext) Get ¶
func (c *BaseContext) Get(key string) interface{}
Get retrieves data from the context.
func (*BaseContext) HTMLBlob ¶
func (c *BaseContext) HTMLBlob(b []byte)
HTMLBlob sends an HTTP blob response.
func (*BaseContext) Handler ¶
func (c *BaseContext) Handler() Handler
Handler returns the matched handler by router.
func (*BaseContext) Header ¶
func (c *BaseContext) Header(key string) string
Header returns value from request headers.
func (*BaseContext) Inline ¶
func (c *BaseContext) Inline(file string, name string)
Inline sends a response as inline
func (*BaseContext) IsTLS ¶
func (c *BaseContext) IsTLS() bool
IsTLS returns true if HTTP connection is TLS otherwise false.
func (*BaseContext) IsWebSocket ¶
func (c *BaseContext) IsWebSocket() bool
IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
func (*BaseContext) JSONBlob ¶
func (c *BaseContext) JSONBlob(b []byte)
JSONBlob sends a JSON blob response.
func (*BaseContext) JSONP ¶
func (c *BaseContext) JSONP(callback string, i interface{})
JSONP sends a JSONP response.
func (*BaseContext) JSONPBlob ¶
func (c *BaseContext) JSONPBlob(callback string, b []byte)
JSONPBlob sends a JSONP blob response.
func (*BaseContext) JSONPretty ¶
func (c *BaseContext) JSONPretty(i interface{}, indent string)
JSONPretty sends a pretty-print JSON.
func (*BaseContext) MultipartForm ¶
func (c *BaseContext) MultipartForm() (*multipart.Form, error)
MultipartForm returns the multipart form.
func (*BaseContext) NativeContext ¶
func (c *BaseContext) NativeContext() interface{}
NativeContext 返回封装的底层上下文对象
func (*BaseContext) NoContent ¶
func (c *BaseContext) NoContent(code int)
NoContent sends a response with no body and a status code.
func (*BaseContext) Path ¶
func (c *BaseContext) Path() string
Path returns the registered path for the handler.
func (*BaseContext) PathParam ¶
func (c *BaseContext) PathParam(name string) string
PathParam returns path parameter by name.
func (*BaseContext) PathParamNames ¶
func (c *BaseContext) PathParamNames() []string
PathParamNames returns path parameter names.
func (*BaseContext) PathParamValues ¶
func (c *BaseContext) PathParamValues() []string
PathParamValues returns path parameter values.
func (*BaseContext) QueryParam ¶
func (c *BaseContext) QueryParam(name string) string
QueryParam returns the query param for the provided name.
func (*BaseContext) QueryParams ¶
func (c *BaseContext) QueryParams() url.Values
QueryParams returns the query parameters as `url.Values`.
func (*BaseContext) QueryString ¶
func (c *BaseContext) QueryString() string
QueryString returns the URL query string.
func (*BaseContext) Redirect ¶
func (c *BaseContext) Redirect(code int, url string)
Redirect redirects the request to a provided URL with status code.
func (*BaseContext) Request ¶
func (c *BaseContext) Request() *http.Request
Request returns `*http.Request`.
func (*BaseContext) RequestBody ¶
func (c *BaseContext) RequestBody() ([]byte, error)
RequestBody return stream data.
func (*BaseContext) Response ¶ added in v1.1.1
func (c *BaseContext) Response() Response
Response returns Response.
func (*BaseContext) SSEvent ¶
func (c *BaseContext) SSEvent(name string, message interface{})
SSEvent writes a Server-Sent Event into the body stream.
func (*BaseContext) SaveUploadedFile ¶
func (c *BaseContext) SaveUploadedFile(file *multipart.FileHeader, dst string) error
SaveUploadedFile uploads the form file to specific dst.
func (*BaseContext) Scheme ¶
func (c *BaseContext) Scheme() string
Scheme returns the HTTP protocol scheme, `http` or `https`.
func (*BaseContext) Set ¶
func (c *BaseContext) Set(key string, val interface{}) error
Set saves data in the context.
func (*BaseContext) SetContentType ¶
func (c *BaseContext) SetContentType(typ string)
SetContentType 设置 ResponseWriter 的 ContentType 。
func (*BaseContext) SetContext ¶ added in v1.1.1
func (c *BaseContext) SetContext(ctx context.Context)
SetContext sets context.Context.
func (*BaseContext) SetCookie ¶
func (c *BaseContext) SetCookie(cookie *http.Cookie)
SetCookie adds a `Set-Cookie` header in HTTP response.
func (*BaseContext) SetHeader ¶
func (c *BaseContext) SetHeader(key, value string)
SetHeader is a intelligent shortcut for c.Writer.Header().Set(key, value).
func (*BaseContext) SetStatus ¶
func (c *BaseContext) SetStatus(code int)
SetStatus sets the HTTP response code.
func (*BaseContext) String ¶
func (c *BaseContext) String(format string, values ...interface{})
String writes the given string into the response body.
func (*BaseContext) XMLBlob ¶
func (c *BaseContext) XMLBlob(b []byte)
XMLBlob sends an XML blob response.
func (*BaseContext) XMLPretty ¶
func (c *BaseContext) XMLPretty(i interface{}, indent string)
XMLPretty sends a pretty-print XML.
type BasicAuthConfig ¶
type BodyBinder ¶ added in v1.1.3
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 Context ¶
type Context interface { // NativeContext 返回封装的底层上下文对象 NativeContext() interface{} // Get retrieves data from the context. Get(key string) interface{} // Set saves data in the context. Set(key string, val interface{}) error // Request returns `*http.Request`. Request() *http.Request // Context 返回 Request 绑定的 context.Context 对象 Context() context.Context // SetContext sets context.Context. SetContext(ctx 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 // Header returns value from request headers. Header(key string) string // Cookies returns the HTTP cookies sent with the request. Cookies() []*http.Cookie // Cookie returns the named cookie provided in the request. Cookie(name string) (*http.Cookie, error) // PathParamNames returns path parameter names. PathParamNames() []string // PathParamValues returns path parameter values. PathParamValues() []string // PathParam returns path parameter by name. PathParam(name string) string // QueryString returns the URL query string. QueryString() string // QueryParams returns the query parameters as `url.Values`. QueryParams() url.Values // QueryParam returns the query param for the provided name. QueryParam(name string) string // FormParams returns the form parameters as `url.Values`. FormParams() (url.Values, error) // FormValue returns the form field value for the provided name. FormValue(name string) string // MultipartForm returns the multipart form. MultipartForm() (*multipart.Form, 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 // RequestBody return stream data. RequestBody() ([]byte, error) // Bind binds the request body into provided type `i`. The default binder // does it based on Content-Type header. Bind(i interface{}) error // Response returns Response. Response() Response // SetStatus sets the HTTP response code. SetStatus(code int) // SetHeader 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)` SetHeader(key, value string) // SetContentType 设置 ResponseWriter 的 ContentType 。 SetContentType(typ 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 ErrorHandler ¶
ErrorHandler 错误处理接口
type FileHandler ¶ added in v1.1.1
func (*FileHandler) FileLine ¶ added in v1.1.1
func (f *FileHandler) FileLine() (file string, line int, fnName string)
func (*FileHandler) Invoke ¶ added in v1.1.1
func (f *FileHandler) Invoke(ctx Context)
type Filter ¶
type Filter interface {
Invoke(ctx Context, chain FilterChain)
}
Filter 过滤器接口,Invoke 通过 chain.Next() 驱动链条向后执行。
func HTTPSNonWWWRedirect ¶
func HTTPSNonWWWRedirect(config RedirectConfig) Filter
func HTTPSRedirect ¶
func HTTPSRedirect(config RedirectConfig) Filter
func HTTPSWWWRedirect ¶
func HTTPSWWWRedirect(config RedirectConfig) Filter
func NewBasicAuthFilter ¶
func NewBasicAuthFilter(config BasicAuthConfig) Filter
NewBasicAuthFilter 创建封装 http 基础认证功能的过滤器。
func NewGzipFilter ¶ added in v1.1.3
NewGzipFilter The compression level can be gzip.DefaultCompression, gzip.NoCompression, gzip.HuffmanOnly or any integer value between gip.BestSpeed and gzip.BestCompression inclusive.
func NewRequestIDFilter ¶
func NewRequestIDFilter(config RequestIDConfig) Filter
func NonWWWRedirect ¶
func NonWWWRedirect(config RedirectConfig) Filter
func WWWRedirect ¶
func WWWRedirect(config RedirectConfig) Filter
type FilterChain ¶
type FilterChain interface {
Next(ctx Context, op NextOperation)
}
FilterChain 过滤器链条接口
func NewFilterChain ¶
func NewFilterChain(filters []Filter) FilterChain
NewFilterChain filterChain 的构造函数
type FilterFunc ¶
type FilterFunc func(ctx Context, chain FilterChain)
type FuncErrorHandler ¶
FuncErrorHandler func 形式定义错误处理接口
func (FuncErrorHandler) Invoke ¶
func (f FuncErrorHandler) Invoke(ctx Context, err *HttpError)
type GzipFilter ¶ added in v1.1.3
type GzipFilter struct { ExcludedExtensions []string ExcludedPaths []string ExcludedPathsRegexes []*regexp.Regexp // contains filtered or unexported fields }
func (*GzipFilter) Invoke ¶ added in v1.1.3
func (f *GzipFilter) Invoke(ctx Context, chain FilterChain)
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 MethodOverrideConfig ¶
type MethodOverrideConfig struct {
// contains filtered or unexported fields
}
func NewMethodOverrideConfig ¶
func NewMethodOverrideConfig() *MethodOverrideConfig
func (*MethodOverrideConfig) ByFormValue ¶
func (config *MethodOverrideConfig) ByFormValue(name string) *MethodOverrideConfig
func (*MethodOverrideConfig) ByHeader ¶
func (config *MethodOverrideConfig) ByHeader(key string) *MethodOverrideConfig
func (*MethodOverrideConfig) ByQueryParam ¶
func (config *MethodOverrideConfig) ByQueryParam(name string) *MethodOverrideConfig
type MethodOverrideGetter ¶
type NextOperation ¶ added in v1.1.3
type NextOperation int
const ( Recursive NextOperation = 0 Iterative = 1 )
type Operation ¶
type Operation interface { // Process 完成处理参数绑定等过程 Process() error }
Operation 与路由绑定的 API 描述文档
type PathStyleEnum ¶
type PathStyleEnum int
type Prefilter ¶
type Prefilter struct {
Filter
}
Prefilter 前置过滤器,用于路由未决策前。
func NewMethodOverrideFilter ¶
func NewMethodOverrideFilter(config *MethodOverrideConfig) *Prefilter
func NewRewriteFilter ¶
func NewRewriteFilter() *Prefilter
type RedirectConfig ¶
type RedirectConfig struct {
Code int
}
func NewRedirectConfig ¶
func NewRedirectConfig() RedirectConfig
type RequestIDConfig ¶
func NewRequestIDConfig ¶
func NewRequestIDConfig() RequestIDConfig
type Response ¶ added in v1.1.1
type Response interface { http.ResponseWriter Get() http.ResponseWriter Set(w http.ResponseWriter) }
type Router ¶
type Router interface { // Mappers 返回映射器列表 Mappers() []*Mapper // AddMapper 添加一个 Mapper AddMapper(m *Mapper) // HttpGet 注册 GET 方法处理函数 HttpGet(path string, h http.HandlerFunc) *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 // HttpPost 注册 POST 方法处理函数 HttpPost(path string, h http.HandlerFunc) *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 // HttpPut 注册 PUT 方法处理函数 HttpPut(path string, h http.HandlerFunc) *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 // HttpDelete 注册 DELETE 方法处理函数 HttpDelete(path string, h http.HandlerFunc) *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 // File 定义单个文件资源 File(path string, file string) *Mapper // Static 定义一组文件资源 Static(prefix string, dir string) *Mapper // StaticFS 定义一组文件资源 StaticFS(prefix string, fs http.FileSystem) *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 Server ¶
type Server interface { Router // Config 获取 web 服务器配置 Config() ServerConfig // Prefilters 返回前置过滤器列表 Prefilters() []*Prefilter // AddPrefilter 添加前置过滤器 AddPrefilter(filter ...*Prefilter) // Filters 返回过滤器列表 Filters() []Filter // AddFilter 添加过滤器 AddFilter(filter ...Filter) // AccessFilter 获取访问记录 Filter AccessFilter() Filter // SetAccessFilter 设置访问记录 Filter SetAccessFilter(filter Filter) // ErrorHandler 获取错误处理接口 ErrorHandler() ErrorHandler // SetErrorHandler 设置错误处理接口 SetErrorHandler(errHandler ErrorHandler) // Swagger 设置与服务器绑定的 Swagger 对象 Swagger(swagger Swagger) // Start 启动 web 服务器 Start() error // Stop 停止 web 服务器 Stop(ctx context.Context) error }
Server web 服务器
type ServerConfig ¶
type ServerConfig struct { Prefix string `value:"${prefix:=}"` // 用于 WebStarter 选择路由匹配的 Server Host string `value:"${host:=}"` // 监听 IP Port int `value:"${port:=8080}"` // HTTP 端口 EnableSSL bool `value:"${ssl.enable:=false}"` // 是否启用 HTTPS KeyFile string `value:"${ssl.key:=}"` // SSL 秘钥 CertFile string `value:"${ssl.cert:=}"` // SSL 证书 BasePath string `value:"${base-path:=}"` // 当前 Server 的所有路由都具有这个路径前缀 ReadTimeout int `value:"${read-timeout:=0}"` // 读取超时,毫秒 WriteTimeout int `value:"${write-timeout:=0}"` // 写入超时,毫秒 }
ServerConfig 定义 web 服务器配置
type ServerHandler ¶
type SimpleResponse ¶ added in v1.1.1
type SimpleResponse struct {
http.ResponseWriter
}
func (*SimpleResponse) Get ¶ added in v1.1.1
func (resp *SimpleResponse) Get() http.ResponseWriter
func (*SimpleResponse) Set ¶ added in v1.1.1
func (resp *SimpleResponse) Set(w http.ResponseWriter)
type Swagger ¶
type Swagger interface { // ReadDoc 读取标准格式的描述文档 ReadDoc() string // AddPath 添加与服务器绑定的路由节点 AddPath(path string, method string, op Operation) }
Swagger 与服务器绑定的 API 描述文档
type SwaggerHandler ¶
SwaggerHandler Swagger 处理器