web

package
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2023 License: MIT Imports: 29 Imported by: 30

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

Functions

func DefaultProvider

func DefaultProvider(routeHandler RouteHandler, options ...Option) infra.DaemonProvider

func DefaultProviderWithListenerBuilder

func DefaultProviderWithListenerBuilder(listenerBuilder infra.ListenerBuilder, routeHandler RouteHandler, options ...Option) infra.DaemonProvider

func Provider

func Provider(builder infra.ListenerBuilder, options ...Option) infra.DaemonProvider

func View

func View(tplPath string, data interface{}) (string, error)

Types

type Config

type Config struct {
	MultipartFormMaxMemory int64  // Multipart-form 解析占用最大内存
	ViewTemplatePathPrefix string // 视图模板目录
	TempDir                string // 临时目录,用于上传文件等
	TempFilePattern        string // 临时文件规则
	IgnoreLastSlash        bool   // 是否忽略 URL 末尾的 /

	HttpWriteTimeout      time.Duration
	HttpIdleTimeout       time.Duration
	HttpReadTimeout       time.Duration
	HttpReadHeaderTimeout time.Duration
	// contains filtered or unexported fields
}

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig create a default config

type Context

type Context interface {
	JSON(res interface{}) *JSONResponse
	NewJSONResponse(res interface{}) *JSONResponse
	YAML(res interface{}) *YAMLResponse
	NewYAMLResponse(res interface{}) *YAMLResponse
	JSONWithCode(res interface{}, code int) *JSONResponse
	Nil() *NilResponse
	API(businessCode string, message string, data interface{}) *JSONResponse
	NewAPIResponse(businessCode string, message string, data interface{}) *JSONResponse
	Raw(func(w http.ResponseWriter)) *RawResponse
	NewRawResponse(func(w http.ResponseWriter)) *RawResponse
	NewHTMLResponse(res string) *HTMLResponse
	HTML(res string) *HTMLResponse
	HTMLWithCode(res string, code int) *HTMLResponse
	Error(res string, code int) *ErrorResponse
	JSONError(res string, code int) *JSONResponse
	NewErrorResponse(res string, code int) *ErrorResponse
	Redirect(location string, code int) *RedirectResponse
	Resolve(callback interface{}) Response
	Decode(v interface{}) error
	Unmarshal(v interface{}) error
	UnmarshalYAML(v interface{}) error
	PathVar(key string) string
	PathVars() map[string]string
	Input(key string) string
	JSONGet(keys ...string) string
	InputWithDefault(key string, defaultVal string) string
	ToInt(val string, defaultVal int) int
	ToInt64(val string, defaultVal int64) int64
	ToFloat32(val string, defaultVal float32) float32
	ToFloat64(val string, defaultVal float64) float64
	IntInput(key string, defaultVal int) int
	Int64Input(key string, defaultVal int64) int64
	Float32Input(key string, defaultVal float32) float32
	Float64Input(key string, defaultVal float64) float64
	File(key string) (*UploadedFile, error)
	IsXMLHTTPRequest() bool
	AJAX() bool
	IsJSON() bool
	ContentType() string
	AllHeaders() http.Header
	Headers(key string) []string
	Header(key string) string
	Is(method string) bool
	IsGet() bool
	IsPost() bool
	IsHead() bool
	IsDelete() bool
	IsPut() bool
	IsPatch() bool
	IsOptions() bool
	Method() string
	Body() []byte
	Set(key string, value interface{})
	Get(key string) interface{}
	Context() context.Context
	Cookie(name string) (*http.Cookie, error)
	Cookies() []*http.Cookie
	Session() *sessions.Session
	Request() Request
	Response() ResponseCreator
	Container() ioc.Container
	View(tplPath string, data interface{}) *HTMLResponse
	Validate(validator Validator, jsonResponse bool)
	RemoteAddr() string

	RouteURL(name string, pairs ...string) (*url.URL, error)
	RouteByName(name string) RouteAware
	CurrentRoute() RouteAware
}

type Controller

type Controller interface {
	// Register register routes for a controller
	Register(router Router)
}

Controller is a interface for controller

type CustomAccessLog

type CustomAccessLog struct {
	Context      Context       `json:"-"`
	Method       string        `json:"method"`
	URL          string        `json:"url"`
	ResponseCode int           `json:"response_code"`
	Elapse       time.Duration `json:"elapse"`
}

type Error

type Error interface {
	Error() string
	StatusCode() int
}

Error is a interface for http error

type ErrorResponse

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

ErrorResponse Error response

func NewErrorResponse

func NewErrorResponse(response ResponseCreator, res string, code int) *ErrorResponse

NewErrorResponse Create error response

func (*ErrorResponse) Code

func (resp *ErrorResponse) Code() int

func (*ErrorResponse) CreateResponse

func (resp *ErrorResponse) CreateResponse() error

CreateResponse 创建响应内容

func (*ErrorResponse) WithCode

func (resp *ErrorResponse) WithCode(code int) *ErrorResponse

WithCode set response code and return itself

type ExceptionHandler

type ExceptionHandler func(ctx Context, err interface{}) Response

ExceptionHandler is a handler using handle exceptions

type HTMLResponse

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

HTMLResponse HTML响应

func NewHTMLResponse

func NewHTMLResponse(response ResponseCreator, code int, res string) *HTMLResponse

NewHTMLResponse 创建HTML响应

func (*HTMLResponse) Code

func (resp *HTMLResponse) Code() int

func (*HTMLResponse) CreateResponse

func (resp *HTMLResponse) CreateResponse() error

CreateResponse 创建响应内容

func (*HTMLResponse) WithCode

func (resp *HTMLResponse) WithCode(code int) *HTMLResponse

WithCode set response code and return itself

type HandlerDecorator

type HandlerDecorator func(WebHandler) WebHandler

HandlerDecorator 该函数是http handler的装饰器

type HttpRequest

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

HttpRequest 请求对象封装

func (*HttpRequest) AJAX

func (req *HttpRequest) AJAX() bool

AJAX return whether the request is a ajax request

func (*HttpRequest) AllHeaders

func (req *HttpRequest) AllHeaders() http.Header

AllHeaders return all http request headers

func (*HttpRequest) Body

func (req *HttpRequest) Body() []byte

Body return request body

func (*HttpRequest) Clear

func (req *HttpRequest) Clear()

Clear all variables in request

func (*HttpRequest) ContentType

func (req *HttpRequest) ContentType() string

ContentType return content type for request

func (*HttpRequest) Context

func (req *HttpRequest) Context() context.Context

Context returns the request's context

func (*HttpRequest) Cookie

func (req *HttpRequest) Cookie(name string) (*http.Cookie, error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found. If multiple cookies match the given name, only one cookie will be returned.

func (*HttpRequest) Cookies

func (req *HttpRequest) Cookies() []*http.Cookie

Cookies parses and returns the HTTP cookies sent with the request.

func (*HttpRequest) CurrentRoute

func (req *HttpRequest) CurrentRoute() RouteAware

CurrentRoute return current route

func (*HttpRequest) Decode

func (req *HttpRequest) Decode(v interface{}) error

Decode decodes form request to a struct

func (*HttpRequest) File

func (req *HttpRequest) File(key string) (*UploadedFile, error)

File Retrieving Uploaded Files

func (*HttpRequest) Float32Input

func (req *HttpRequest) Float32Input(key string, defaultVal float32) float32

Float32Input return a float32 form parameter

func (*HttpRequest) Float64Input

func (req *HttpRequest) Float64Input(key string, defaultVal float64) float64

Float64Input return a float64 form parameter

func (*HttpRequest) Get

func (req *HttpRequest) Get(key string) interface{}

Get 从当前请求提取设置的变量

func (*HttpRequest) HTTPRequest

func (req *HttpRequest) HTTPRequest() *http.Request

HTTPRequest return a http.request

func (*HttpRequest) Header

func (req *HttpRequest) Header(key string) string

Header gets the first value associated with the given key.

func (*HttpRequest) Headers

func (req *HttpRequest) Headers(key string) []string

Headers gets all values associated with given key

func (*HttpRequest) Input

func (req *HttpRequest) Input(key string) string

Input return form parameter from request

func (*HttpRequest) InputWithDefault

func (req *HttpRequest) InputWithDefault(key string, defaultVal string) string

InputWithDefault return a form parameter with a default value

func (*HttpRequest) Int64Input

func (req *HttpRequest) Int64Input(key string, defaultVal int64) int64

Int64Input return a integer form parameter

func (*HttpRequest) IntInput

func (req *HttpRequest) IntInput(key string, defaultVal int) int

IntInput return a integer form parameter

func (*HttpRequest) Is

func (req *HttpRequest) Is(method string) bool

Is 判断请求方法

func (*HttpRequest) IsDelete

func (req *HttpRequest) IsDelete() bool

IsDelete 判断是是否是Delete请求

func (*HttpRequest) IsGet

func (req *HttpRequest) IsGet() bool

IsGet 判断是否是Get请求

func (*HttpRequest) IsHead

func (req *HttpRequest) IsHead() bool

IsHead 判断是否是HEAD请求

func (*HttpRequest) IsJSON

func (req *HttpRequest) IsJSON() bool

IsJSON return whether the request is a json request

func (*HttpRequest) IsOptions

func (req *HttpRequest) IsOptions() bool

IsOptions 判断是否是Options请求

func (*HttpRequest) IsPatch

func (req *HttpRequest) IsPatch() bool

IsPatch 判断是否是Patch请求

func (*HttpRequest) IsPost

func (req *HttpRequest) IsPost() bool

IsPost 判断是否是Post请求

func (*HttpRequest) IsPut

func (req *HttpRequest) IsPut() bool

IsPut 判断是否是Put请求

func (*HttpRequest) IsXMLHTTPRequest

func (req *HttpRequest) IsXMLHTTPRequest() bool

IsXMLHTTPRequest return whether the request is a ajax request

func (*HttpRequest) JSONGet

func (req *HttpRequest) JSONGet(keys ...string) string

func (*HttpRequest) Method

func (req *HttpRequest) Method() string

Method 获取请求方法

func (*HttpRequest) PathVar

func (req *HttpRequest) PathVar(key string) string

PathVar return a path parameter

func (*HttpRequest) PathVars

func (req *HttpRequest) PathVars() map[string]string

PathVars return all path parameters

func (*HttpRequest) Raw

func (req *HttpRequest) Raw() *http.Request

Raw get the underlying http.request

func (*HttpRequest) RemoteAddr added in v1.1.3

func (req *HttpRequest) RemoteAddr() string

RemoteAddr return remote address

func (*HttpRequest) RouteByName

func (req *HttpRequest) RouteByName(name string) RouteAware

RouteByName get a route by name

func (*HttpRequest) RouteURL

func (req *HttpRequest) RouteURL(name string, pairs ...string) (*url.URL, error)

RouteURL builds a URL for the route

func (*HttpRequest) Session

func (req *HttpRequest) Session() *sessions.Session

Session return session instance

func (*HttpRequest) Set

func (req *HttpRequest) Set(key string, value interface{})

Set 设置一个变量,存储到当前请求

func (*HttpRequest) SetSession

func (req *HttpRequest) SetSession(session *sessions.Session)

SetSession set a session to request

func (*HttpRequest) ToFloat32

func (req *HttpRequest) ToFloat32(val string, defaultVal float32) float32

func (*HttpRequest) ToFloat64

func (req *HttpRequest) ToFloat64(val string, defaultVal float64) float64

func (*HttpRequest) ToInt

func (req *HttpRequest) ToInt(val string, defaultVal int) int

func (*HttpRequest) ToInt64

func (req *HttpRequest) ToInt64(val string, defaultVal int64) int64

func (*HttpRequest) Unmarshal

func (req *HttpRequest) Unmarshal(v interface{}) error

Unmarshal request body as json object result must be reference to a variable

func (*HttpRequest) UnmarshalYAML

func (req *HttpRequest) UnmarshalYAML(v interface{}) error

UnmarshalYAML unmarshal request body as yaml object result must be reference to a variable

func (*HttpRequest) Validate

func (req *HttpRequest) Validate(validator Validator, jsonResponse bool)

Validate execute a validator, if there has an error, panic error to framework

type HttpResponse

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

HttpResponse is a response object which wrap http.ResponseWriter

func (*HttpResponse) Cookie

func (resp *HttpResponse) Cookie(cookie *http.Cookie)

Cookie set cookie

func (*HttpResponse) Flush

func (resp *HttpResponse) Flush()

Flush send all response contents to client

func (*HttpResponse) GetCode

func (resp *HttpResponse) GetCode() int

GetCode get response code

func (*HttpResponse) Header

func (resp *HttpResponse) Header(key, value string)

Header set response header

func (*HttpResponse) Raw

func (resp *HttpResponse) Raw() http.ResponseWriter

func (*HttpResponse) ResponseWriter

func (resp *HttpResponse) ResponseWriter() http.ResponseWriter

ResponseWriter return the http.ResponseWriter

func (*HttpResponse) SetCode

func (resp *HttpResponse) SetCode(code int)

SetCode set response code

func (*HttpResponse) SetContent

func (resp *HttpResponse) SetContent(content []byte)

SetContent set response content

type InitHandler

type InitHandler func(resolver infra.Resolver, webServer Server, conf *Config) error

type JSONAble

type JSONAble interface {
	// ToJSON convert a value to jsonable struct or map/array/slice etc
	ToJSON() interface{}
}

JSONAble identify a value can convert to json object

type JSONError

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

JSONError is a error object which implements Error and JSONAble interface

func WrapJSONError

func WrapJSONError(err error, code int) JSONError

WrapJSONError wrap a error to JSONError

func (JSONError) Error

func (apiErr JSONError) Error() string

func (JSONError) StatusCode

func (apiErr JSONError) StatusCode() int

func (JSONError) ToJSON

func (apiErr JSONError) ToJSON() interface{}

type JSONResponse

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

JSONResponse json响应

func NewJSONResponse

func NewJSONResponse(response ResponseCreator, code int, res interface{}) *JSONResponse

NewJSONResponse 创建JSONResponse对象

func (*JSONResponse) Code

func (resp *JSONResponse) Code() int

func (*JSONResponse) CreateResponse

func (resp *JSONResponse) CreateResponse() error

CreateResponse create response

func (*JSONResponse) WithCode

func (resp *JSONResponse) WithCode(code int) *JSONResponse

WithCode set response code and return itself

type M

type M map[string]interface{}

M represents a kv response items

type MiddlewareRouter

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

func (*MiddlewareRouter) Controllers

func (mr *MiddlewareRouter) Controllers(prefix string, controllers ...Controller)

func (*MiddlewareRouter) Group

func (mr *MiddlewareRouter) Group(prefix string, f func(rou Router))

type MuxRouteHandler

type MuxRouteHandler func(resolver infra.Resolver, router *mux.Router)

type NilResponse

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

NilResponse 空响应

func NewNilResponse

func NewNilResponse(response ResponseCreator) *NilResponse

NewNilResponse create a RawResponse

func (*NilResponse) Code

func (resp *NilResponse) Code() int

func (*NilResponse) CreateResponse

func (resp *NilResponse) CreateResponse() error

CreateResponse flush response to client

func (*NilResponse) Response

func (resp *NilResponse) Response() ResponseCreator

response get real response object

type Option

type Option func(cc infra.Resolver, conf *Config)

func SetExceptionHandlerOption

func SetExceptionHandlerOption(h ExceptionHandler) Option

SetExceptionHandlerOption 设置 Server APP 异常处理器

func SetHttpIdleTimeoutOption

func SetHttpIdleTimeoutOption(t time.Duration) Option

SetHttpIdleTimeoutOption set Http idle timeout

func SetHttpReadTimeoutOption

func SetHttpReadTimeoutOption(t time.Duration) Option

SetHttpReadTimeoutOption set Http read timeout

func SetHttpWriteTimeoutOption

func SetHttpWriteTimeoutOption(t time.Duration) Option

SetHttpWriteTimeoutOption set Http write timeout

func SetIgnoreLastSlashOption

func SetIgnoreLastSlashOption(ignore bool) Option

SetIgnoreLastSlashOption 忽略路由地址末尾的 /

func SetInitHandlerOption

func SetInitHandlerOption(h InitHandler) Option

SetInitHandlerOption 初始化阶段,web 应用对象还没有创建,在这里可以更新 web 配置

func SetMultipartFormMaxMemoryOption

func SetMultipartFormMaxMemoryOption(max int64) Option

SetMultipartFormMaxMemoryOption Multipart-form 解析占用最大内存

func SetMuxRouteHandlerOption

func SetMuxRouteHandlerOption(h MuxRouteHandler) Option

SetMuxRouteHandlerOption 路由注册 Main,该方法获取到的是底层的 Gorilla Mux 对象

func SetOptions

func SetOptions(setter func(cc infra.Resolver) []Option) Option

SetOptions 设置 options,设置前可以获取到 infra.Resolver 实例

func SetRouteHandlerOption

func SetRouteHandlerOption(h RouteHandler) Option

SetRouteHandlerOption 路由注册 Main,在该 Main 中注册 API 路由规则

func SetServerConfigOption added in v1.1.2

func SetServerConfigOption(h ServerConfigHandler) Option

SetServerConfigOption 服务初始化阶段,web 服务对象已经创建,此时不能再更新 web 配置了

func SetTempFileOption

func SetTempFileOption(tempDir, tempFilePattern string) Option

SetTempFileOption 设置临时文件规则

type PlainError

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

PlainError is a error object which implements Error interface

func WrapPlainError

func WrapPlainError(err error, code int) PlainError

WrapPlainError warps an error only have message and code

func (PlainError) Error

func (p PlainError) Error() string

func (PlainError) StatusCode

func (p PlainError) StatusCode() int

type RawResponse

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

RawResponse 原生响应

func NewRawResponse

func NewRawResponse(response ResponseCreator, handler func(w http.ResponseWriter)) *RawResponse

NewRawResponse create a RawResponse

func (*RawResponse) Code

func (resp *RawResponse) Code() int

func (*RawResponse) CreateResponse

func (resp *RawResponse) CreateResponse() error

CreateResponse flush response to client

func (*RawResponse) Response

func (resp *RawResponse) Response() ResponseCreator

Response get real response object

type RedirectResponse

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

RedirectResponse 页面跳转

func NewRedirectResponse

func NewRedirectResponse(response ResponseCreator, request Request, location string, code int) *RedirectResponse

NewRedirectResponse 创建RedirectResponse对象

func (*RedirectResponse) Code

func (resp *RedirectResponse) Code() int

func (*RedirectResponse) CreateResponse

func (resp *RedirectResponse) CreateResponse() error

CreateResponse 创建响应内容

func (*RedirectResponse) WithCode

func (resp *RedirectResponse) WithCode(code int) *RedirectResponse

WithCode set response code and return itself

type Request

type Request interface {
	Raw() *http.Request
	Decode(v interface{}) error
	Unmarshal(v interface{}) error
	UnmarshalYAML(v interface{}) error
	PathVar(key string) string
	PathVars() map[string]string
	Input(key string) string
	JSONGet(keys ...string) string
	InputWithDefault(key string, defaultVal string) string
	ToInt(val string, defaultVal int) int
	ToInt64(val string, defaultVal int64) int64
	ToFloat32(val string, defaultVal float32) float32
	ToFloat64(val string, defaultVal float64) float64
	IntInput(key string, defaultVal int) int
	Int64Input(key string, defaultVal int64) int64
	Float32Input(key string, defaultVal float32) float32
	Float64Input(key string, defaultVal float64) float64
	File(key string) (*UploadedFile, error)
	IsXMLHTTPRequest() bool
	AJAX() bool
	IsJSON() bool
	ContentType() string
	AllHeaders() http.Header
	Headers(key string) []string
	Header(key string) string
	Is(method string) bool
	IsGet() bool
	IsPost() bool
	IsHead() bool
	IsDelete() bool
	IsPut() bool
	IsPatch() bool
	IsOptions() bool
	Method() string
	Body() []byte
	Set(key string, value interface{})
	Get(key string) interface{}

	Context() context.Context
	Cookie(name string) (*http.Cookie, error)
	Cookies() []*http.Cookie
	Session() *sessions.Session
	SetSession(session *sessions.Session)

	RouteURL(name string, pairs ...string) (*url.URL, error)
	RouteByName(name string) RouteAware
	CurrentRoute() RouteAware

	Validate(validator Validator, jsonResponse bool)
	RemoteAddr() string
}

type RequestMiddleware

type RequestMiddleware struct{}

RequestMiddleware is a middleware collections

func NewRequestMiddleware

func NewRequestMiddleware() RequestMiddleware

NewRequestMiddleware create a new RequestMiddleware

func (RequestMiddleware) AccessLog

func (rm RequestMiddleware) AccessLog(logger infra.Logger) HandlerDecorator

AccessLog create an access log middleware

func (RequestMiddleware) AfterInterceptor

func (rm RequestMiddleware) AfterInterceptor(fn func(ctx Context, resp Response) Response) HandlerDecorator

AfterInterceptor is a interceptor intercept a response before it's been sent to user

func (RequestMiddleware) AuthHandler

func (rm RequestMiddleware) AuthHandler(cb func(ctx Context, typ string, credential string) error) HandlerDecorator

AuthHandler is a middleware for http auth typ is one of: Basic (see RFC 7617, base64-encoded credentials. See below for more information.), Bearer (see RFC 6750, bearer tokens to access OAuth 2.0-protected resources), Digest (see RFC 7616, only md5 hashing is supported in Firefox, see bug 472823 for SHA encryption support), HOBA (see RFC 7486, Section 3, HTTP Origin-Bound Authentication, digital-signature-based), Mutual (see RFC 8120), AWS4-HMAC-SHA256 (see AWS docs).

func (RequestMiddleware) BeforeInterceptor

func (rm RequestMiddleware) BeforeInterceptor(fn func(ctx Context) Response) HandlerDecorator

BeforeInterceptor is a interceptor intercept a request before processing

func (RequestMiddleware) CORS

func (rm RequestMiddleware) CORS(origin string) HandlerDecorator

CORS create a CORS middleware

func (RequestMiddleware) CustomAccessLog

func (rm RequestMiddleware) CustomAccessLog(fn func(cal CustomAccessLog)) HandlerDecorator

CustomAccessLog create a custom access log handler middleware

func (RequestMiddleware) Session

func (rm RequestMiddleware) Session(store sessions.Store, name string, options *sessions.Options) HandlerDecorator

Session is a middleware for session support

type Response

type Response interface {
	CreateResponse() error
	Code() int
}

Response is the response interface

func DefaultExceptionHandler

func DefaultExceptionHandler(ctx Context, err interface{}) Response

DefaultExceptionHandler is a default implementation for ExceptionHandler

func ErrorToResponse

func ErrorToResponse(ctx Context, err interface{}) (Response, error)

ErrorToResponse convert an error to Response

type ResponseCreator

type ResponseCreator interface {
	Raw() http.ResponseWriter
	SetCode(code int)
	ResponseWriter() http.ResponseWriter
	SetContent(content []byte)
	Header(key, value string)
	Cookie(cookie *http.Cookie)
	GetCode() int
	Flush()
}

ResponseCreator is a response creator

type Route

type Route struct {
	Name             string   `json:"name"`
	Methods          []string `json:"methods"`
	PathTemplate     string   `json:"path_template"`
	PathRegexp       string   `json:"path_regexp"`
	QueriesRegexp    []string `json:"queries_regexp"`
	QueriesTemplates []string `json:"queries_templates"`
	HostTemplate     string   `json:"host_template"`
}

Route is a route represent for query all routes

func GetAllRoutes

func GetAllRoutes(router *mux.Router) []Route

GetAllRoutes return all routes

type RouteAware

type RouteAware interface {
	SkipClean() bool
	GetName() string
	URL(pairs ...string) (*url.URL, error)
	URLHost(pairs ...string) (*url.URL, error)
	URLPath(pairs ...string) (*url.URL, error)
	GetPathTemplate() (string, error)
	GetPathRegexp() (string, error)
	GetQueriesRegexp() ([]string, error)
	GetQueriesTemplates() ([]string, error)
	GetMethods() ([]string, error)
	GetHostTemplate() (string, error)
}

type RouteHandler

type RouteHandler func(resolver infra.Resolver, router Router, mw RequestMiddleware)

type RouteRule

type RouteRule interface {
	Custom(custom func(rou *mux.Route)) RouteRule
	Name(name string) RouteRule
	Headers(pairs ...string) RouteRule
	Queries(pairs ...string) RouteRule
	Schemes(schemes ...string) RouteRule
	Host(tpl string) RouteRule
	Path(path string) RouteRule
	Decorators(dec ...HandlerDecorator) RouteRule

	GetName() string
	GetHost() string
	GetQueries() []string
	GetSchemas() []string
	GetHeaders() []string
	GetCustom() func(rou *mux.Route)
	GetDecorators() []HandlerDecorator
	GetWebHandler() WebHandler
	GetPath() string
	GetMethod() string
}

type Router

type Router interface {
	Group(prefix string, f func(router Router), decors ...HandlerDecorator)
	Perform(exceptionHandler ExceptionHandler, cb func(*mux.Router)) http.Handler
	GetRoutes() []RouteRule
	Any(path string, handler interface{}, middlewares ...HandlerDecorator) RouteRule
	Get(path string, handler interface{}, middlewares ...HandlerDecorator) RouteRule
	Post(path string, handler interface{}, middlewares ...HandlerDecorator) RouteRule
	Delete(path string, handler interface{}, middlewares ...HandlerDecorator) RouteRule
	Put(path string, handler interface{}, middlewares ...HandlerDecorator) RouteRule
	Patch(path string, handler interface{}, middlewares ...HandlerDecorator) RouteRule
	Head(path string, handler interface{}, middlewares ...HandlerDecorator) RouteRule
	Options(path string, handler interface{}, middlewares ...HandlerDecorator) RouteRule

	Controllers(prefix string, controllers ...Controller)
	WithMiddleware(decors ...HandlerDecorator) *MiddlewareRouter
}

func NewRouter

func NewRouter(conf *Config, decorators ...HandlerDecorator) Router

NewRouter 创建一个路由器

func NewRouterWithContainer

func NewRouterWithContainer(c ioc.Container, conf *Config, decorators ...HandlerDecorator) Router

NewRouterWithContainer 创建一个路由器,带有依赖注入容器支持

type Server

type Server interface {
	Start(listener net.Listener) error
	Options(cc infra.Resolver, options ...Option)
}

func NewServer

func NewServer(cc infra.Container, options ...Option) Server

NewServer create a new serverImpl

type ServerConfigHandler added in v1.1.2

type ServerConfigHandler func(server *http.Server, listener net.Listener)

type ServerStatus

type ServerStatus int

type UploadedFile

type UploadedFile struct {
	Header   *multipart.FileHeader
	SavePath string
}

UploadedFile 上传的文件

func (*UploadedFile) Delete

func (file *UploadedFile) Delete() error

Delete 删除文件

func (*UploadedFile) Extension

func (file *UploadedFile) Extension() string

Extension get the file's extension.

func (*UploadedFile) GetTempFilename

func (file *UploadedFile) GetTempFilename() string

GetTempFilename 获取文件临时保存的地址

func (*UploadedFile) Name

func (file *UploadedFile) Name() string

Name 获取上传的文件名

func (*UploadedFile) Size

func (file *UploadedFile) Size() int64

Size 获取文件大小

func (*UploadedFile) Store

func (file *UploadedFile) Store(path string) error

Store the uploaded file on a filesystem disk.

type Validator

type Validator interface {
	Validate(request Request) error
}

Validator is an interface for validator

type WebContext

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

WebContext 作为一个web请求的上下文信息

func (*WebContext) AJAX

func (ctx *WebContext) AJAX() bool

AJAX is a proxy to request.AJAX

func (*WebContext) API

func (ctx *WebContext) API(businessCode string, message string, data interface{}) *JSONResponse

API is a shortcut for NewAPIResponse func

func (*WebContext) AllHeaders

func (ctx *WebContext) AllHeaders() http.Header

AllHeaders is a proxy to request.AllHeaders

func (*WebContext) Body

func (ctx *WebContext) Body() []byte

Body is a proxy to request.Body

func (*WebContext) Container

func (ctx *WebContext) Container() ioc.Container

Container return underlying ioc.Container

func (*WebContext) ContentType

func (ctx *WebContext) ContentType() string

ContentType is a proxy to request.ContentType

func (*WebContext) Context

func (ctx *WebContext) Context() context.Context

Context returns the request's context

func (*WebContext) Cookie

func (ctx *WebContext) Cookie(name string) (*http.Cookie, error)

Cookie returns the named cookie provided in the request or ErrNoCookie if not found. If multiple cookies match the given name, only one cookie will be returned.

func (*WebContext) Cookies

func (ctx *WebContext) Cookies() []*http.Cookie

Cookies parses and returns the HTTP cookies sent with the request.

func (*WebContext) CurrentRoute

func (ctx *WebContext) CurrentRoute() RouteAware

func (*WebContext) Decode

func (ctx *WebContext) Decode(v interface{}) error

Decode decodes form request to a struct

func (*WebContext) Error

func (ctx *WebContext) Error(res string, code int) *ErrorResponse

Error is a shortcut for NewErrorResponse func

func (*WebContext) File

func (ctx *WebContext) File(key string) (*UploadedFile, error)

File is a proxy to request.File

func (*WebContext) Float32Input

func (ctx *WebContext) Float32Input(key string, defaultVal float32) float32

Float32Input is a proxy to request.Float32Input

func (*WebContext) Float64Input

func (ctx *WebContext) Float64Input(key string, defaultVal float64) float64

Float64Input is a proxy to request.Float64Input

func (*WebContext) Get

func (ctx *WebContext) Get(key string) interface{}

Get is a proxy to request.Get

func (*WebContext) HTML

func (ctx *WebContext) HTML(res string) *HTMLResponse

HTML is a shortcut for NewHTMLResponse func

func (*WebContext) HTMLWithCode

func (ctx *WebContext) HTMLWithCode(res string, code int) *HTMLResponse

HTMLWithCode create a HTMLResponse with http status code

func (*WebContext) Header

func (ctx *WebContext) Header(key string) string

Header is a proxy to request.Header

func (*WebContext) Headers

func (ctx *WebContext) Headers(key string) []string

Headers is a proxy to request.Headers

func (*WebContext) Input

func (ctx *WebContext) Input(key string) string

Input is a proxy to request.Input

func (*WebContext) InputWithDefault

func (ctx *WebContext) InputWithDefault(key string, defaultVal string) string

InputWithDefault is a proxy to request.InputWithDefault

func (*WebContext) Int64Input

func (ctx *WebContext) Int64Input(key string, defaultVal int64) int64

Int64Input is a proxy to request.Int64Input

func (*WebContext) IntInput

func (ctx *WebContext) IntInput(key string, defaultVal int) int

IntInput is a proxy to request.IntInput

func (*WebContext) Is

func (ctx *WebContext) Is(method string) bool

Is is a proxy to request.Is

func (*WebContext) IsDelete

func (ctx *WebContext) IsDelete() bool

IsDelete is a proxy to request.IsDelete

func (*WebContext) IsGet

func (ctx *WebContext) IsGet() bool

IsGet is a proxy to request.IsGet

func (*WebContext) IsHead

func (ctx *WebContext) IsHead() bool

IsHead is a proxy to request.IsHead

func (*WebContext) IsJSON

func (ctx *WebContext) IsJSON() bool

IsJSON is a proxy to request.IsJSON

func (*WebContext) IsOptions

func (ctx *WebContext) IsOptions() bool

IsOptions is a proxy to request.IsOptions

func (*WebContext) IsPatch

func (ctx *WebContext) IsPatch() bool

IsPatch is a proxy to request.IsPatch

func (*WebContext) IsPost

func (ctx *WebContext) IsPost() bool

IsPost is a proxy to request.IsPost

func (*WebContext) IsPut

func (ctx *WebContext) IsPut() bool

IsPut is a proxy to request.IsPut

func (*WebContext) IsXMLHTTPRequest

func (ctx *WebContext) IsXMLHTTPRequest() bool

IsXMLHTTPRequest is a proxy to IsXMLHTTPRequest

func (*WebContext) JSON

func (ctx *WebContext) JSON(res interface{}) *JSONResponse

JSON is a shortcut for NewJSONResponse func

func (*WebContext) JSONError

func (ctx *WebContext) JSONError(res string, code int) *JSONResponse

JSONError return a json error response for error

func (*WebContext) JSONGet

func (ctx *WebContext) JSONGet(keys ...string) string

JSONGet is a proxy to request.JSONGet

func (*WebContext) JSONWithCode

func (ctx *WebContext) JSONWithCode(res interface{}, code int) *JSONResponse

JSONWithCode create a json response with a http status code

func (*WebContext) Method

func (ctx *WebContext) Method() string

Method is a proxy to request.Method

func (*WebContext) NewAPIResponse

func (ctx *WebContext) NewAPIResponse(businessCode string, message string, data interface{}) *JSONResponse

NewAPIResponse create a new APIResponse

func (*WebContext) NewErrorResponse

func (ctx *WebContext) NewErrorResponse(res string, code int) *ErrorResponse

NewErrorResponse create a error response

func (*WebContext) NewHTMLResponse

func (ctx *WebContext) NewHTMLResponse(res string) *HTMLResponse

NewHTMLResponse create a new HTMLResponse

func (*WebContext) NewJSONResponse

func (ctx *WebContext) NewJSONResponse(res interface{}) *JSONResponse

NewJSONResponse create a new JSONResponse with the http status code equal 200

func (*WebContext) NewRawResponse

func (ctx *WebContext) NewRawResponse(handler func(w http.ResponseWriter)) *RawResponse

NewRawResponse create a new RawResponse

func (*WebContext) NewYAMLResponse

func (ctx *WebContext) NewYAMLResponse(res interface{}) *YAMLResponse

NewYAMLResponse create a new YAMLResponse with http status code equal 200

func (*WebContext) Nil

func (ctx *WebContext) Nil() *NilResponse

Nil return a NilResponse

func (*WebContext) PathVar

func (ctx *WebContext) PathVar(key string) string

PathVar is a proxy to request.PathVar

func (*WebContext) PathVars

func (ctx *WebContext) PathVars() map[string]string

PathVars is a proxy to request.PathVars

func (*WebContext) Raw

func (ctx *WebContext) Raw(handler func(w http.ResponseWriter)) *RawResponse

Raw create a new RawResponse

func (*WebContext) Redirect

func (ctx *WebContext) Redirect(location string, code int) *RedirectResponse

Redirect replies to the request with a redirect to url

func (*WebContext) RemoteAddr added in v1.1.3

func (ctx *WebContext) RemoteAddr() string

func (*WebContext) Request

func (ctx *WebContext) Request() Request

Request return underlying Request

func (*WebContext) Resolve

func (ctx *WebContext) Resolve(callback interface{}) Response

Resolve resolve implements dependency injection for http handler

func (*WebContext) Response

func (ctx *WebContext) Response() ResponseCreator

Response return underlying Response

func (*WebContext) RouteByName

func (ctx *WebContext) RouteByName(name string) RouteAware

func (*WebContext) RouteURL

func (ctx *WebContext) RouteURL(name string, pairs ...string) (*url.URL, error)

func (*WebContext) Session

func (ctx *WebContext) Session() *sessions.Session

Session return session instance

func (*WebContext) Set

func (ctx *WebContext) Set(key string, value interface{})

Set is a proxy to request.setData

func (*WebContext) ToFloat32

func (ctx *WebContext) ToFloat32(val string, defaultVal float32) float32

ToFloat32 is a proxy to request.ToFloat32

func (*WebContext) ToFloat64

func (ctx *WebContext) ToFloat64(val string, defaultVal float64) float64

ToFloat64 is a proxy to request.ToFloat64

func (*WebContext) ToInt

func (ctx *WebContext) ToInt(val string, defaultVal int) int

ToInt is a proxy to request.ToInt

func (*WebContext) ToInt64

func (ctx *WebContext) ToInt64(val string, defaultVal int64) int64

ToInt64 is a proxy to request.ToInt64

func (*WebContext) Unmarshal

func (ctx *WebContext) Unmarshal(v interface{}) error

Unmarshal is a proxy to request.Unmarshal

func (*WebContext) UnmarshalYAML

func (ctx *WebContext) UnmarshalYAML(v interface{}) error

UnmarshalYAML is a proxy to request.UnmarshalYAML

func (*WebContext) Validate

func (ctx *WebContext) Validate(validator Validator, jsonResponse bool)

Validate execute a validator, if error happens, panic it

func (*WebContext) View

func (ctx *WebContext) View(tplPath string, data interface{}) *HTMLResponse

View is a helper function for template rendering

func (*WebContext) YAML

func (ctx *WebContext) YAML(res interface{}) *YAMLResponse

YAML is a shortcut for NewYAMLResponse func

type WebHandler

type WebHandler func(context Context) Response

WebHandler 控制器方法

type WebSocket

type WebSocket struct {
	WS    *websocket.Conn
	Error error
}

type YAMLResponse

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

YAMLResponse yaml响应

func NewYAMLResponse

func NewYAMLResponse(response ResponseCreator, code int, res interface{}) *YAMLResponse

NewYAMLResponse 创建YAMLResponse对象

func (*YAMLResponse) Code

func (resp *YAMLResponse) Code() int

func (*YAMLResponse) CreateResponse

func (resp *YAMLResponse) CreateResponse() error

CreateResponse create response

func (*YAMLResponse) WithCode

func (resp *YAMLResponse) WithCode(code int) *YAMLResponse

WithCode set response code and return itself

Jump to

Keyboard shortcuts

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