web

package
v1.1.0-rc2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2021 License: Apache-2.0 Imports: 19 Imported by: 18

Documentation

Overview

Package web 为社区优秀的 Web 服务器提供一个抽象层,使得底层可以灵活切换。

Index

Constants

View Source
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"
)
View Source
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
)
View Source
const (
	EchoPathStyle = PathStyleEnum(0)
	GinPathStyle  = PathStyleEnum(1)
	JavaPathStyle = PathStyleEnum(2)
)
View Source
const ContextKey = "@WebCtx"

ContextKey Context 和 NativeContext 相互转换的 Key

View Source
const DefaultWildCardName = "@_@"

DefaultWildCardName 默认通配符的名称

View Source
const ReplaySessionID = "REPLAY-SESSION-ID"

ReplaySessionID 流量回放模式下传递会话 ID 使用的 Header 。

Variables

View Source
var (
	ERROR   = NewRpcError(-1, "ERROR")
	SUCCESS = NewRpcSuccess(200, "SUCCESS")
	DEFAULT = NewErrorCode(math.MaxInt32, "DEFAULT")
)
View Source
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 用户自定义错误处理函数

View Source
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 GetMethod

func GetMethod(method uint32) (r []string)

GetMethod 返回 method 对应的 HTTP 方法

func InvokeHandler

func InvokeHandler(ctx Context, fn Handler, filters []Filter)

InvokeHandler 执行 Web 处理函数

func NewRouter

func NewRouter() *router

NewRouter router 的构造函数。

func RegisterSwaggerHandler

func RegisterSwaggerHandler(handler SwaggerHandler)

RegisterSwaggerHandler 注册 Swagger 处理器

func StartRecord

func StartRecord(ctx Context)

StartRecord 启动流量录制

func StartReplay

func StartReplay(ctx Context)

StartReplay 开始流量回放

func StopRecord

func StopRecord(ctx Context)

StopRecord 停止流量录制

func StopReplay

func StopReplay(ctx Context)

StopReplay 停止流量回放

func ToPathStyle

func ToPathStyle(path string, style PathStyleEnum) (string, string)

ToPathStyle 将 URL 转换为指定风格的表示形式

func URLPatterns

func URLPatterns(filters []Filter) (*urlPatterns, error)

URLPatterns 根据 Filter 的 URL 匹配表达式进行分组。

func WithFileLine

func WithFileLine(err error, skip int) error

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) Address

func (c *AbstractContainer) Address() string

Address 返回监听地址

func (*AbstractContainer) Config

func (c *AbstractContainer) Config() ContainerConfig

Config 获取 Web 容器配置

func (*AbstractContainer) DeleteBinding

func (r *AbstractContainer) DeleteBinding(path string, fn interface{}) *Mapper

DeleteBinding 注册 DELETE 方法处理函数

func (*AbstractContainer) DeleteMapping

func (r *AbstractContainer) DeleteMapping(path string, fn HandlerFunc) *Mapper

DeleteMapping 注册 DELETE 方法处理函数

func (*AbstractContainer) GetBinding

func (r *AbstractContainer) GetBinding(path string, fn interface{}) *Mapper

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

func (r *AbstractContainer) HandleDelete(path string, h Handler) *Mapper

HandleDelete 注册 DELETE 方法处理函数

func (*AbstractContainer) HandleGet

func (r *AbstractContainer) HandleGet(path string, h Handler) *Mapper

HandleGet 注册 GET 方法处理函数

func (*AbstractContainer) HandlePost

func (r *AbstractContainer) HandlePost(path string, h Handler) *Mapper

HandlePost 注册 POST 方法处理函数

func (*AbstractContainer) HandlePut

func (r *AbstractContainer) HandlePut(path string, h Handler) *Mapper

HandlePut 注册 PUT 方法处理函数

func (*AbstractContainer) HandleRequest

func (r *AbstractContainer) HandleRequest(method uint32, path string, h Handler) *Mapper

HandleRequest 注册任意 HTTP 方法处理函数

func (*AbstractContainer) Mappers

func (r *AbstractContainer) Mappers() []*Mapper

Mappers 返回映射器列表

func (*AbstractContainer) PostBinding

func (r *AbstractContainer) PostBinding(path string, fn interface{}) *Mapper

PostBinding 注册 POST 方法处理函数

func (*AbstractContainer) PostMapping

func (r *AbstractContainer) PostMapping(path string, fn HandlerFunc) *Mapper

PostMapping 注册 POST 方法处理函数

func (*AbstractContainer) PutBinding

func (r *AbstractContainer) PutBinding(path string, fn interface{}) *Mapper

PutBinding 注册 PUT 方法处理函数

func (*AbstractContainer) PutMapping

func (r *AbstractContainer) PutMapping(path string, fn HandlerFunc) *Mapper

PutMapping 注册 PUT 方法处理函数

func (*AbstractContainer) RequestBinding

func (r *AbstractContainer) RequestBinding(method uint32, path string, fn interface{}) *Mapper

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) Start

func (c *AbstractContainer) Start() error

Start 启动 Web 容器

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 ErrorCode

type ErrorCode struct {
	Code int32  `json:"code"` // 错误码
	Msg  string `json:"msg"`  // 错误信息
}

ErrorCode 错误码

func NewErrorCode

func NewErrorCode(code int32, msg string) ErrorCode

NewErrorCode ErrorCode 的构造函数

type Filter

type Filter interface {
	Invoke(ctx Context, chain FilterChain)
}

Filter 过滤器接口,Invoke 通过 chain.Next() 驱动链条向后执行。

func HandlerFilter

func HandlerFilter(fn Handler) Filter

HandlerFilter 把 Web 处理接口转换成过滤器

type FilterChain

type FilterChain interface {
	Next(ctx Context)
}

FilterChain 过滤器链条接口

type Handler

type Handler interface {

	// Invoke 响应函数
	Invoke(Context)

	// FileLine 获取用户函数的文件名、行号以及函数名称
	FileLine() (file string, line int, fnName string)
}

Handler 标准 Web 处理接口

func BIND

func BIND(fn interface{}) Handler

BIND 转换成 BIND 形式的 Web 处理接口

func FUNC

func FUNC(fn HandlerFunc) Handler

FUNC 标准 Web 处理函数的辅助函数

func HTTP

func HTTP(fn http.HandlerFunc) Handler

HTTP 标准 Http 处理函数的辅助函数

func WrapF

func WrapF(fn http.HandlerFunc) Handler

WrapF 标准 Http 处理函数的辅助函数

func WrapH

func WrapH(h http.Handler) Handler

WrapH 标准 Http 处理函数的辅助函数

type HandlerFunc

type HandlerFunc func(Context)

HandlerFunc 标准 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

func NewHttpError(code int, message ...string) *HttpError

NewHttpError creates a new HttpError instance.

func (*HttpError) Error

func (e *HttpError) Error() string

Error makes it compatible with `error` interface.

func (*HttpError) SetInternal

func (e *HttpError) SetInternal(err error) *HttpError

SetInternal sets error to HTTPError.Internal

type Mapper

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

Mapper 路由映射器

func NewMapper

func NewMapper(method uint32, path string, h Handler) *Mapper

NewMapper Mapper 的构造函数

func (*Mapper) Handler

func (m *Mapper) Handler() Handler

Handler 返回 Mapper 的处理函数

func (*Mapper) Method

func (m *Mapper) Method() uint32

Method 返回 Mapper 的方法

func (*Mapper) Operation

func (m *Mapper) Operation(op Operation)

Operation 设置与 Mapper 绑定的 Operation 对象

func (*Mapper) Path

func (m *Mapper) Path() string

Path 返回 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 NewRpcError

func NewRpcError(code int32, msg string) RpcError

NewRpcError RpcError 的构造函数

func (RpcError) Error

func (r RpcError) Error(err error) *RpcResult

Error 绑定一个错误

func (RpcError) ErrorWithData

func (r RpcError) ErrorWithData(err error, data interface{}) *RpcResult

ErrorWithData 绑定一个错误和一个值

func (RpcError) Panic

func (r RpcError) Panic(err error) *util.PanicCond

Panic 抛出一个异常值

func (RpcError) PanicImmediately

func (r RpcError) PanicImmediately(err error)

PanicImmediately 立即抛出一个异常值

func (RpcError) Panicf

func (r RpcError) Panicf(format string, a ...interface{}) *util.PanicCond

Panicf 抛出一段需要格式化的错误字符串

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 的构造函数

func (RpcSuccess) Data

func (r RpcSuccess) Data(data interface{}) *RpcResult

Data 绑定一个值

type Swagger

type Swagger interface {

	// ReadDoc 读取标准格式的描述文档
	ReadDoc() string

	// AddPath 添加与容器绑定的路由节点
	AddPath(path string, method string, op Operation)
}

Swagger 与容器绑定的 API 描述文档

type SwaggerHandler

type SwaggerHandler func(router Router, doc string)

SwaggerHandler Swagger 处理器

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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