web

package
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2022 License: Apache-2.0 Imports: 30 Imported by: 18

README

web

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

Installation

go get github.com/go-spring/spring-core@v1.1.0-rc2 

Import

import "github.com/go-spring/spring-core/web"

Example

普通路由
package main

import (
	"fmt"

	"github.com/go-spring/spring-core/gs"
	"github.com/go-spring/spring-core/web"
	_ "github.com/go-spring/starter-echo"
)

func main() {
	gs.GetMapping("/a/b/c", func(ctx web.Context) {
		ctx.String("OK")
	})
	fmt.Println(gs.Run())
}
➜ curl http://127.0.0.1:8080/a/b/c
OK
java 风格路由
package main

import (
	"fmt"

	"github.com/go-spring/spring-core/gs"
	"github.com/go-spring/spring-core/web"
	_ "github.com/go-spring/starter-echo"
)

func main() {
	gs.GetMapping("/:a/b/:c/{*:d}", func(ctx web.Context) {
		ctx.String("a=%s b=%s *=%s\n", ctx.PathParam("a"), ctx.PathParam("c"), ctx.PathParam("*"))
		ctx.String("a=%s b=%s *=%s\n", ctx.PathParam("a"), ctx.PathParam("c"), ctx.PathParam("d"))
	})
	fmt.Println(gs.Run())
}
➜ curl http://127.0.0.1:8080/a/b/c/d
a=a b=c *=d
a=a b=c *=d
echo 风格路由
package main

import (
	"fmt"

	"github.com/go-spring/spring-core/gs"
	"github.com/go-spring/spring-core/web"
	_ "github.com/go-spring/starter-echo"
)

func main() {
	gs.GetMapping("/:a/b/:c/*", func(ctx web.Context) {
		ctx.String("a=%s c=%s *=%s", ctx.PathParam("a"), ctx.PathParam("c"), ctx.PathParam("*"))
	})
	fmt.Println(gs.Run())
}
➜ curl http://127.0.0.1:8080/a/b/c/d
a=a c=c *=d
gin 风格路由
package main

import (
	"fmt"

	"github.com/go-spring/spring-core/gs"
	"github.com/go-spring/spring-core/web"
	_ "github.com/go-spring/starter-echo"
)

func main() {
	gs.GetMapping("/:a/b/:c/*d", func(ctx web.Context) {
		ctx.String("a=%s b=%s *=%s\n", ctx.PathParam("a"), ctx.PathParam("c"), ctx.PathParam("*"))
		ctx.String("a=%s b=%s *=%s\n", ctx.PathParam("a"), ctx.PathParam("c"), ctx.PathParam("d"))
	})
	fmt.Println(gs.Run())
}
➜ curl http://127.0.0.1:8080/a/b/c/d
a=a b=c *=d
a=a b=c *=d
文件服务器
package main

import (
	"fmt"
	"net/http"

	"github.com/go-spring/spring-core/gs"
	"github.com/go-spring/spring-core/web"
	_ "github.com/go-spring/starter-echo"
)

func main() {
	gs.HandleGet("/public/*", web.WrapH(http.StripPrefix("/public/", http.FileServer(http.Dir("public")))))
	fmt.Println(gs.Run())
}

然后在项目下创建一个 public 目录,里面创建一个内容为 hello world! 的 a.txt 文件。

➜ curl http://127.0.0.1:8080/public/a.txt
hello world!
BIND 模式
package main

import (
	"context"
	"fmt"

	"github.com/go-spring/spring-core/gs"
	"github.com/go-spring/spring-core/web"
	_ "github.com/go-spring/starter-echo"
)

type HelloReq struct {
	Name string `form:"name"`
}

type HelloResp struct {
	Body string `json:"body"`
}

func main() {
	gs.GetBinding("/hello", func(ctx context.Context, req *HelloReq) *web.RpcResult {
		return web.SUCCESS.Data(&HelloResp{Body: "hello " + req.Name + "!"})
	})
	fmt.Println(gs.Run())
}
➜ curl 'http://127.0.0.1:8080/hello?name=lvan100' 
{"code":200,"msg":"SUCCESS","data":{"body":"hello lvan100!"}}
中间件
Basic Auth
package main

import (
	"fmt"

	"github.com/go-spring/spring-core/gs"
	"github.com/go-spring/spring-core/web"
	"github.com/go-spring/spring-echo"
	_ "github.com/go-spring/starter-echo"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

func main() {

	gs.Provide(func( /* 可以通过配置将用户名密码传进来 */ ) web.Filter {
		m := middleware.BasicAuth(func(u string, p string, e echo.Context) (bool, error) {
			if u == "lvan100" && p == "123456" {
				return true, nil
			}
			return false, nil
		})
		return SpringEcho.Filter(m)
	})

	gs.GetMapping("/hello", func(ctx web.Context) {
		ctx.String("hello %s!", ctx.QueryParam("name"))
	})

	fmt.Println(gs.Run())
}
➜ curl 'http://127.0.0.1:8080/hello?name=lvan100'
Unauthorized
➜ curl 'http://127.0.0.1:8080/hello?name=lvan100' -H'Authorization: Basic bHZhbjEwMDoxMjM0NTY='
{"code":200,"msg":"SUCCESS","data":{"body":"hello lvan100!"}}

Documentation

Overview

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

Index

Constants

View Source
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"
)
View Source
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"
)
View Source
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"
)
View Source
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"
)
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 (
	AuthUserKey = "::user::"
)
View Source
const (
	CharsetUTF8 = "charset=UTF-8"
)
View Source
const ContextKey = "@@WebCtx@@"

ContextKey Context 和 NativeContext 相互转换的 Key

View Source
const DefaultWildcardName = "@_@"

DefaultWildcardName 默认通配符的名称

Variables

View Source
var (
	ERROR   = NewRpcError(-1, "ERROR")
	SUCCESS = NewRpcSuccess(200, "SUCCESS")
	DEFAULT = NewErrorCode(math.MaxInt32, "DEFAULT")
)
View Source
var RPCInvoke = func(ctx Context, fn func(Context) interface{}) {
	ctx.JSON(fn(ctx))
}

RPCInvoke 可自定义的 rpc 执行函数。

Functions

func Bind added in v1.1.3

func Bind(i interface{}, ctx Context) error

func BindForm added in v1.1.3

func BindForm(i interface{}, ctx Context) error

func BindJSON added in v1.1.3

func BindJSON(i interface{}, ctx Context) error

func BindXML added in v1.1.3

func BindXML(i interface{}, ctx Context) error

func FuncFilter

func FuncFilter(f FilterFunc) *funcFilter

FuncFilter 封装 func 形式的过滤器。

func GetHTTPRequest

func GetHTTPRequest(ctx context.Context) *http.Request

GetHTTPRequest returns the *http.Request storing in the context.Context.

func GetMethod

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

GetMethod 返回 method 对应的 HTTP 方法

func NewRouter

func NewRouter() *router

NewRouter router 的构造函数。

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 RegisterScopeBinder(scope BindScope, tag string)

func RegisterSwaggerHandler

func RegisterSwaggerHandler(handler SwaggerHandler)

RegisterSwaggerHandler 注册 Swagger 处理器

func ToPathStyle

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

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

func URLPatternFilter

func URLPatternFilter(f Filter, s ...string) *urlPatternFilter

URLPatternFilter 封装带 URLPatterns 信息的过滤器。

func URLPatterns

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

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

func WithFileLine

func WithFileLine(err error, skip int) error

WithFileLine 返回错误发生的文件行号,skip 是相对于当前函数的深度。

Types

type BaseContext

type BaseContext struct {
	Logger *log.Logger
	// contains filtered or unexported fields
}

func NewBaseContext

func NewBaseContext(path string, handler Handler, r *http.Request, w Response) *BaseContext

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

func (c *BaseContext) HTML(html string)

HTML sends an HTTP response.

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

func (c *BaseContext) JSON(i interface{})

JSON sends a JSON response.

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

func (c *BaseContext) XML(i interface{})

XML sends an XML response.

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 BasicAuthConfig struct {
	Accounts map[string]string
	Realm    string
}

type BindScope added in v1.1.3

type BindScope int
const (
	BindScopeURI BindScope = iota
	BindScopeQuery
	BindScopeHeader
	BindScopeBody
)

type BodyBinder added in v1.1.3

type BodyBinder func(i interface{}, ctx Context) error

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 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 ErrorHandler

type ErrorHandler interface {
	Invoke(ctx Context, err *HttpError)
}

ErrorHandler 错误处理接口

type FileHandler added in v1.1.1

type FileHandler struct {
	Prefix string
	Server http.Handler
}

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 HandlerFilter

func HandlerFilter(fn Handler) Filter

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

func NewBasicAuthFilter

func NewBasicAuthFilter(config BasicAuthConfig) Filter

NewBasicAuthFilter 创建封装 http 基础认证功能的过滤器。

func NewGzipFilter added in v1.1.3

func NewGzipFilter(level int) (Filter, error)

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

type FuncErrorHandler func(ctx Context, err *HttpError)

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 处理接口

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 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 MethodOverrideGetter func(ctx Context) string

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 FuncPrefilter

func FuncPrefilter(f FilterFunc) *Prefilter

FuncPrefilter 封装前置过滤器,用于路由未决策前。

func NewMethodOverrideFilter

func NewMethodOverrideFilter(config *MethodOverrideConfig) *Prefilter

func NewPrefilter

func NewPrefilter(f Filter) *Prefilter

NewPrefilter 封装前置过滤器,用于路由未决策前。

func NewRewriteFilter

func NewRewriteFilter() *Prefilter

type RedirectConfig

type RedirectConfig struct {
	Code int
}

func NewRedirectConfig

func NewRedirectConfig() RedirectConfig

type RequestIDConfig

type RequestIDConfig struct {
	Header    string
	Generator func() string
}

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 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 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 ServerHandler interface {
	http.Handler
	Start(s Server) error
	RecoveryFilter(errHandler ErrorHandler) Filter
}

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

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