Documentation ¶
Index ¶
- Constants
- Variables
- func GenerateETag(lastModified time.Time, size int64) string
- func GenerateETag2(lastModified time.Time, size int64, fileName string) string
- func MethodIndex(method string) int
- func SetRender(r Render)
- type CORSConfig
- type Context
- func (ctx *Context) Abort(code int)
- func (ctx *Context) Attachment(name string, modtime time.Time, content io.ReadSeeker, inline ...bool)
- func (ctx *Context) BadRequest()
- func (ctx *Context) Bind(obj interface{}) error
- func (ctx *Context) BindWith(obj interface{}, b binding.Bindinger) error
- func (ctx *Context) BodyBytes() ([]byte, error)
- func (ctx *Context) BodyString() (string, error)
- func (ctx *Context) ContentType() string
- func (ctx *Context) Cookie(name string) string
- func (ctx *Context) CookieBool(name string) bool
- func (ctx *Context) CookieEscape(name string) string
- func (ctx *Context) CookieFloat64(name string) float64
- func (ctx *Context) CookieInt(name string) int
- func (ctx *Context) CookieInt64(name string) int64
- func (ctx *Context) CookieUint(name string) uint
- func (ctx *Context) CookieUint64(name string) uint64
- func (ctx *Context) Data(code int, contentType string, data []byte)
- func (ctx *Context) DefaultQuery(name, defaultValue string) string
- func (ctx *Context) DefaultQueryArray(name string, defaultValue []string) []string
- func (ctx *Context) DefaultQueryBool(name, defaultValue string) bool
- func (ctx *Context) DefaultQueryFloat64(name, defaultValue string) float64
- func (ctx *Context) DefaultQueryInt(name, defaultValue string) int
- func (ctx *Context) DefaultQueryInt64(name, defaultValue string) int64
- func (ctx *Context) DefaultQueryMap(key string, defaultValue map[string]string) map[string]string
- func (ctx *Context) DefaultQueryUint(name, defaultValue string) uint
- func (ctx *Context) DefaultQueryUint64(name, defaultValue string) uint64
- func (ctx *Context) Download(fpath string, inline ...bool) error
- func (ctx *Context) File(filepath string)
- func (ctx *Context) Forbidden()
- func (ctx *Context) FormFile(name string) (multipart.File, *multipart.FileHeader, error)
- func (ctx *Context) Found(uri string)
- func (ctx *Context) FullPath() string
- func (c *Context) Get(name string) interface{}
- func (ctx *Context) GetHeader(key string) string
- func (c *Context) GetMaybe(name string) (value interface{}, exists bool)
- func (ctx *Context) HTML(code int, name string, data interface{})
- func (ctx *Context) HTMLRaw(code int, str string)
- func (ctx *Context) HTMLSet(code int, setName, tplName string, data interface{})
- func (ctx *Context) HandlerName() string
- func (ctx *Context) InternalServerError()
- func (ctx *Context) IsAjax() bool
- func (ctx *Context) IsWebsocket() bool
- func (ctx *Context) JSON(code int, v interface{}) error
- func (ctx *Context) MovedPermanently(uri string)
- func (ctx *Context) Next()
- func (ctx *Context) NoCache()
- func (ctx *Context) NotFound()
- func (ctx *Context) NotModified()
- func (ctx *Context) Param(key string) string
- func (ctx *Context) ParseFormOrMultipartForm()
- func (ctx *Context) Protocol() string
- func (ctx *Context) Proxy() []string
- func (ctx *Context) Query(name string) string
- func (ctx *Context) QueryArray(name string) []string
- func (ctx *Context) QueryBool(name string) bool
- func (ctx *Context) QueryFloat64(name string) float64
- func (ctx *Context) QueryInt(name string) int
- func (ctx *Context) QueryInt64(name string) int64
- func (ctx *Context) QueryMap(key string) map[string]string
- func (ctx *Context) QueryUint(name string) uint
- func (ctx *Context) QueryUint64(name string) uint64
- func (ctx *Context) ReadCloser() io.ReadCloser
- func (ctx *Context) RealIp() string
- func (ctx *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
- func (ctx *Context) ServeFile(filePath string)
- func (c *Context) Set(name string, value interface{})
- func (ctx *Context) SetCookie(name string, value string, others ...interface{})
- func (ctx *Context) SetHeader(key, value string)
- func (ctx *Context) Status() int
- func (ctx *Context) Stream(contentType string, r io.Reader) error
- func (ctx *Context) String(code int, str string)
- func (ctx *Context) Unauthorized()
- func (ctx *Context) UserAgent() string
- func (ctx *Context) Write(data []byte) (int, error)
- func (ctx *Context) WriteHeader(code int)
- func (ctx *Context) Written() bool
- func (ctx *Context) XML(code int, v interface{}) error
- type ETagType
- type Engine
- func (e *Engine) ListenAndServe(addr string) error
- func (e *Engine) ListenAndServeTLS(addr, certFile, keyFile string) error
- func (e *Engine) PrintRawAllRoutes()
- func (e *Engine) PrintRawRouter()
- func (e *Engine) PrintRawRoutes(method string)
- func (e *Engine) PrintRouterTree(method string)
- func (e *Engine) Run(addr ...string) error
- func (e *Engine) RunTLS(addr, certFile, keyFile string) error
- func (e *Engine) ServeHTTP(rw http.ResponseWriter, req *http.Request)
- type Environ
- func (m Environ) Get(name string) interface{}
- func (m Environ) GetBool(name string) bool
- func (m Environ) GetFloat64(name string) float64
- func (m Environ) GetInt(name string) int
- func (m Environ) GetInt64(name string) int64
- func (m Environ) GetString(name string) string
- func (m Environ) GetUint(name string) uint
- func (m Environ) GetUint64(name string) uint64
- func (m Environ) Has(name string) bool
- func (m Environ) Set(name string, v interface{})
- type H
- type Handler
- type HandlerFunc
- type Option
- type Params
- func (p Params) Bool(name string) (bool, error)
- func (p Params) Float64(name string) (float64, error)
- func (p Params) Int(name string) (int, error)
- func (p Params) Int64(name string) (int64, error)
- func (p Params) MustBool(name string) bool
- func (p Params) MustFloat64(name string) float64
- func (p Params) MustInt(name string) int
- func (p Params) MustInt64(name string) int64
- func (p Params) MustUint(name string) uint
- func (p Params) MustUint64(name string) uint64
- func (p Params) String(name string) string
- func (p Params) Uint(name string) (uint, error)
- func (p Params) Uint64(name string) (uint64, error)
- type Render
- type ResponseWriter
- type Router
- func (r *Router) ANY(pattern string, handlers ...interface{})
- func (r *Router) Before(handlers ...interface{})
- func (r *Router) Classic()
- func (r *Router) DELETE(pattern string, handlers ...interface{})
- func (r *Router) GET(pattern string, handlers ...interface{})
- func (r *Router) Group(pattern string, is ...interface{}) *Router
- func (r *Router) HEAD(pattern string, handlers ...interface{})
- func (r *Router) Handler(opts ...Option) *Engine
- func (r *Router) IsParent() bool
- func (r *Router) OPTIONS(pattern string, handlers ...interface{})
- func (r *Router) PATCH(pattern string, handlers ...interface{})
- func (r *Router) POST(pattern string, handlers ...interface{})
- func (r *Router) PUT(pattern string, handlers ...interface{})
- func (r *Router) Static(uri, root string)
- func (r *Router) StaticAdvance(opt *StaticOptions)
- func (r *Router) StaticFile(relativePath, filepath string)
- func (r *Router) Use(handlers ...interface{})
- type StaticOptions
Constants ¶
const ( MIMESeparator = "; " CharsetUTF8 = "charset=utf-8" )
const ( MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + MIMESeparator + CharsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + MIMESeparator + CharsetUTF8 MIMETextHTML = "text/html" MIMETextHTMLCharsetUTF8 = MIMETextHTML + MIMESeparator + CharsetUTF8 MIMETextPlain = "text/plain" MIMETextPlainCharsetUTF8 = MIMETextPlain + MIMESeparator + CharsetUTF8 MIMEXMLHttpRequest = "XMLHttpRequest" )
MIME types
const ( HeaderCacheControl = "Cache-Control" // Requests, Responses HeaderContentType = "Content-Type" // Requests, Responses HeaderUserAgent = "User-Agent" // Requests HeaderXRequestedWith = "X-Requested-With" // Requests HeaderExpires = "Expires" // Responses HeaderContentDisposition = "Content-Disposition" // Responses // Common Non-Standard Response Headers HeaderXForwardedFor = "X-Forwarded-For" // Requests HeaderXForwardedProto = "X-Forwarded-Proto" // Requests HeaderXRealIP = "X-Real-IP" // Requests )
HTTP Header Fields, from chrome see https://github.com/teambition/gear/blob/master/const.go
const ( HeaderVary = "Vary" HeaderOrigin = "Origin" // Access control HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" )
const ( ETagTypeNone = iota ETagType1 ETagType2 )
const ( Stable = "stable" Dev = "dev" )
all status
const (
DEFAULT_TPL_SET_NAME = ""
)
const (
VERSION = "2.0.0"
)
version
Variables ¶
var ( LogColor = true LogClose = false LogHttpBody = true LogTimeFormat = "2006-01-02 15:04:05" )
var ( // DefaultCORSConfig is the default CORS middleware config. DefaultCORSConfig = CORSConfig{ AllowOrigins: []string{"*"}, AllowMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodHead}, } )
var (
MethodAnyExclude = []string{http.MethodHead, http.MethodOptions}
)
var Status = Dev
current status
Functions ¶
func GenerateETag ¶
GenerateETag generates an ETag based on file modification time and size from http://lxr.nginx.org/ident?_i=ngx_http_set_etag
func GenerateETag2 ¶
GenerateETag2 generates an ETag based on file modification time, size, filename
func MethodIndex ¶
Types ¶
type CORSConfig ¶
type CORSConfig struct { // AllowOrigin defines a list of origins that may access the resource. // Optional. Default value []string{"*"}. AllowOrigins []string `json:"allow_origins"` // AllowMethods defines a list methods allowed when accessing the resource. // This is used in response to a preflight request. // Optional. Default value DefaultCORSConfig.AllowMethods. AllowMethods []string `json:"allow_methods"` // AllowHeaders defines a list of request headers that can be used when // making the actual request. This in response to a preflight request. // Optional. Default value []string{}. AllowHeaders []string `json:"allow_headers"` // AllowCredentials indicates whether or not the response to the request // can be exposed when the credentials flag is true. When used as part of // a response to a preflight request, this indicates whether or not the // actual request can be made using credentials. // Optional. Default value false. AllowCredentials bool `json:"allow_credentials"` // ExposeHeaders defines a whitelist headers that clients are allowed to // access. // Optional. Default value []string{}. ExposeHeaders []string `json:"expose_headers"` // MaxAge indicates how long (in seconds) the results of a preflight request // can be cached. // Optional. Default value 0. MaxAge int `json:"max_age"` }
CORSConfig defines the config for CORS middleware.
type Context ¶
type Context struct { Environ Environ Params Params Request *http.Request ResponseWriter // contains filtered or unexported fields }
Context represents the context of current request of water instance. Context体现了water处理当前请求时的上下文环境 不在Context中使用"Resp ResponseWriter"的原因:Resp.Write()和Ctx.Write()的行为不一致, 因Resp.Write()不会设置ctx.written,导致在Recovery()等地方重复调用WriteHeader而报错 "http: multiple response.WriteHeader calls".
func (*Context) Attachment ¶
func (*Context) BodyString ¶
BodyString returns content of request body in string.
func (*Context) ContentType ¶
ContentType returns the Content-Type header of the request.
func (*Context) CookieBool ¶
func (*Context) CookieEscape ¶
func (*Context) CookieFloat64 ¶
func (*Context) CookieInt64 ¶
func (*Context) CookieUint ¶
func (*Context) CookieUint64 ¶
func (*Context) DefaultQuery ¶
DefaultQuery returns trimmed string, but no name return default Note: It is recommended! If not, you can use "ctx.Request.FormValue". 这是推荐的做法,如果不认同,可使用ctx.Request.FormValue.
func (*Context) DefaultQueryArray ¶
DefaultQueryArray returns a list of results by given query name
func (*Context) DefaultQueryBool ¶
DefaultQueryBool returns bool
func (*Context) DefaultQueryFloat64 ¶
DefaultQueryFloat64 returns float64
func (*Context) DefaultQueryInt ¶
DefaultQueryInt returns int
func (*Context) DefaultQueryInt64 ¶
DefaultQueryInt64 returns int64
func (*Context) DefaultQueryMap ¶
DefaultQueryMap returns a map for a given query key.
func (*Context) DefaultQueryUint ¶
DefaultQueryUint returns uint
func (*Context) DefaultQueryUint64 ¶
DefaultQueryUint64 returns uint64
func (*Context) FullPath ¶
FullPath returns a matched route full path. For not found routes returns an empty string
func (*Context) GetMaybe ¶
GetMaybe returns the value for the given name, ie: (value, true). If the value does not exists it returns (nil, false)
func (*Context) HandlerName ¶
HandlerName returns the last handler's name. For example if the handler is "_Users()", this function will return "main._Users".
func (*Context) IsWebsocket ¶
func (*Context) NoCache ¶
func (ctx *Context) NoCache()
http://stackoverflow.com/questions/49547/making-sure-a-web-page-is-not-cached-across-all-browsers
func (*Context) Param ¶
Param returns the value of the URL param. It is a shortcut for c.Params.String(key)
router.GET("/user/<id>", func(c *water.Context) { // a GET request to /user/john id := c.Param("id") // id == "john" })
func (*Context) ParseFormOrMultipartForm ¶
func (ctx *Context) ParseFormOrMultipartForm()
ParseFormOrMultipartForm parses the raw query from the URL.
func (*Context) Protocol ¶
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto
func (*Context) Query ¶
Query returns trimmed string. Note: It is recommended! If not, you can use "ctx.Request.FormValue". 这是推荐的做法,如果不认同,可使用ctx.Request.FormValue.
func (*Context) QueryArray ¶
QueryArray returns a list of results by given query name
func (*Context) QueryFloat64 ¶
QueryFloat64 returns float64
func (*Context) QueryInt64 ¶
QueryInt64 returns int64
func (*Context) QueryMap ¶
QueryMap returns a map for a given query key. POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1 Content-Type: application/x-www-form-urlencoded names[first]=thinkerou&names[second]=tianou
func (*Context) QueryUint64 ¶
QueryUint64 returns uint64
func (*Context) ReadCloser ¶
func (ctx *Context) ReadCloser() io.ReadCloser
ReadCloser returns a ReadCloser for request body, need Close()
func (*Context) SaveUploadedFile ¶
func (ctx *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
// Upload the file to specific dst. c.SaveUploadedFile(file, dst) }
curl -X POST http://localhost:8080/upload \ -F "upload[]=@/Users/appleboy/test1.zip" \ -F "upload[]=@/Users/appleboy/test2.zip" \ -H "Content-Type: multipart/form-data"
func (*Context) SetCookie ¶
name/value escape by url.QueryEscape() before SetCookie() if necessary others... : MaxAge, Path, Domain, Secure, HttpOnly, SameSite. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.
func (*Context) WriteHeader ¶
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
--- water ---
func (*Engine) ListenAndServe ¶
Run start web service Deprecated: please use Run()
func (*Engine) ListenAndServeTLS ¶
Run start web service with tls Deprecated: please use RunTLS()
func (*Engine) PrintRawAllRoutes ¶
func (e *Engine) PrintRawAllRoutes()
order by add router order output: [method : count(handler)] uri
func (*Engine) PrintRawRouter ¶
func (e *Engine) PrintRawRouter()
output: uri [method : count(handler)]
func (*Engine) PrintRawRoutes ¶
print routes by method order by uri output: [count(handler)] uri
func (*Engine) PrintRouterTree ¶
print release router tree by method len(tree.handlers) includes middleware
type Environ ¶
type Environ map[string]interface{}
a set of environment variables. 存储water的环境变量
func (Environ) GetFloat64 ¶
type Handler ¶
type Handler interface {
ServeHTTP(*Context)
}
func WrapHandler ¶
func WrapHandler(handler interface{}) Handler
WrapHandlerFunc wrap func to HandlerFunc
type HandlerFunc ¶
type HandlerFunc func(*Context)
func CORS ¶
func CORS(config CORSConfig) HandlerFunc
func Logger ¶
func Logger() HandlerFunc
func Recovery ¶
func Recovery() HandlerFunc
func (HandlerFunc) ServeHTTP ¶
func (f HandlerFunc) ServeHTTP(ctx *Context)
type Option ¶
type Option func(*options)
func WithMaxMultipartMemory ¶
WithMaxMultipartMemory is given to http.Request's ParseMultipartForm method call.
func WithNoFoundHandlers ¶
func WithNoFoundHandlers(hs ...interface{}) Option
WithNoFoundHandlers the handler for no match route, example: vue spa code=404, can use middleware
func WithStaticRouter ¶
WithStaticRouter for the scene of multi status route 适用于多静态路由的场景
type Params ¶
func (Params) MustFloat64 ¶
MustFloat64 returns float64l
func (Params) MustUint64 ¶
MustUint64 returns uint64.
type ResponseWriter ¶
type ResponseWriter interface { http.ResponseWriter }
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
multiway tree
func Default ¶
func Default() *Router
Default returns an router instance with the Logger and Recovery middleware already attached.
func (*Router) Before ¶
func (r *Router) Before(handlers ...interface{})
Before for global middleware, include handle middleware before match routes and 404
func (*Router) Static ¶
Static serves files from the given file system root. http.NotFound is used instead of the Router's NotFound handler. use :
router.Static("/static", "/var/www")
func (*Router) StaticAdvance ¶
func (r *Router) StaticAdvance(opt *StaticOptions)
Static serves files from the given file system root. http.NotFound is used instead of the Router's NotFound handler. can send expires, etag, index
func (*Router) StaticFile ¶
StaticFile registers a single route in order to serve a single file router.StaticFile("favicon.ico", "./resources/favicon.ico")
type StaticOptions ¶
type StaticOptions struct { // Prefix is the optional prefix used to serve the static directory content Prefix string // IndexFile defines which file to serve as index if it exists. IndexFile string // Expires defines which user-defined function to use for producing a HTTP Expires Header Expires func() string // ETag defines if we should add an ETag header ETag ETagType // FileSystem is the interface for supporting any implmentation of file system. FileSystem http.FileSystem // contains filtered or unexported fields }
StaticOptions is a struct for specifying configuration options for the Static Files middleware.