Documentation ¶
Overview ¶
Package zen ... zen is a elegant and lightweight webframe for go backend development
Index ¶
- Constants
- func CleanPath(p string) string
- func SetLogLevel(level string)
- func SetLogOutput(out io.Writer)
- func StatusText(code int) string
- func UnWrapF(h HandlerFunc) http.HandlerFunc
- type Context
- func (ctx *Context) BindJSON(input interface{}) error
- func (ctx *Context) BindXML(input interface{}) error
- func (ctx *Context) Do(job func() error) error
- func (ctx *Context) Dup(c context.Context) Context
- func (ctx *Context) Form(key string) string
- func (ctx *Context) GetValue(key interface{}) interface{}
- func (ctx *Context) JSON(i interface{}) (err error)
- func (ctx *Context) LogError(args ...interface{})
- func (ctx *Context) LogErrorf(format string, args ...interface{})
- func (ctx *Context) LogInfo(args ...interface{})
- func (ctx *Context) LogInfof(format string, args ...interface{})
- func (ctx *Context) Param(key string) string
- func (ctx *Context) ParseValidateForm(input interface{}) error
- func (ctx *Context) SetField(key string, val interface{})
- func (ctx *Context) SetValue(key, val interface{})
- func (ctx *Context) WithCancel() (Context, context.CancelFunc)
- func (ctx *Context) WithDeadline(dead time.Time) (Context, context.CancelFunc)
- func (ctx *Context) WriteData(contentType string, data []byte)
- func (ctx *Context) WriteFile(filepath string)
- func (ctx *Context) WriteHeader(k, v string)
- func (ctx *Context) WriteStatus(code int)
- func (ctx *Context) WriteString(s string)
- func (ctx *Context) XML(i interface{}) (err error)
- type HandlerFunc
- type Middleware
- type Middlewares
- type Option
- func SetHandleMethodNotAllowed(b bool) Option
- func SetHandleOPTIONS(b bool) Option
- func SetReadHeaderTimeout(t time.Duration) Option
- func SetReadTimeout(t time.Duration) Option
- func SetRedirectFixedPath(b bool) Option
- func SetRedirectTrailingSlash(b bool) Option
- func SetTimeout(t time.Duration) Option
- func SetWriteTimeout(t time.Duration) Option
- type Param
- type Params
- type Router
- type Server
- func (s *Server) AddInterceptor(handler Middleware)
- func (s *Server) Close() error
- func (s *Server) Group(base string, interceptors ...Middleware) Router
- func (s *Server) HandleNotAllowed(handler HandlerFunc)
- func (s *Server) HandleNotFound(handler HandlerFunc)
- func (s *Server) Lookup(method, path string) (HandlerFunc, Params, bool)
- func (s *Server) Run(addr string) error
- func (s *Server) RunTLS(addr string, certFile string, keyFile string) error
- func (s *Server) ServeHTTP(rw http.ResponseWriter, r *http.Request)
- func (s *Server) Shutdown() error
- func (s *Server) Static(staticpath string, dir string)
Constants ¶
const ( 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" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXForwardedFor = "X-Forwarded-For" HeaderXRealIP = "X-Real-IP" HeaderServer = "Server" HeaderOrigin = "Origin" 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" // Security HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXXSSProtection = "X-XSS-Protection" HeaderXFrameOptions = "X-Frame-Options" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderXCSRFToken = "X-CSRF-Token" )
Headers
const ( MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8 MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + 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" )
MIME types
const ( // CONNECT : http method CONNECT CONNECT = "CONNECT" // DELETE : http method DELETE DELETE = "DELETE" // GET : http method GET GET = "GET" // HEAD : http method HEAD HEAD = "HEAD" // OPTIONS : http method OPTIONS OPTIONS = "OPTIONS" // PATCH : http method PATCH PATCH = "PATCH" // POST : http method POST POST = "POST" // PUT : http method PUT PUT = "PUT" // TRACE : http method TRACE TRACE = "TRACE" )
const ( StatusContinue = 100 // RFC 7231, 6.2.1 StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2 StatusProcessing = 102 // RFC 2518, 10.1 StatusOK = 200 // RFC 7231, 6.3.1 StatusCreated = 201 // RFC 7231, 6.3.2 StatusAccepted = 202 // RFC 7231, 6.3.3 StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4 StatusNoContent = 204 // RFC 7231, 6.3.5 StatusResetContent = 205 // RFC 7231, 6.3.6 StatusPartialContent = 206 // RFC 7233, 4.1 StatusMultiStatus = 207 // RFC 4918, 11.1 StatusAlreadyReported = 208 // RFC 5842, 7.1 StatusIMUsed = 226 // RFC 3229, 10.4.1 StatusMultipleChoices = 300 // RFC 7231, 6.4.1 StatusMovedPermanently = 301 // RFC 7231, 6.4.2 StatusFound = 302 // RFC 7231, 6.4.3 StatusSeeOther = 303 // RFC 7231, 6.4.4 StatusNotModified = 304 // RFC 7232, 4.1 StatusUseProxy = 305 // RFC 7231, 6.4.5 StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7 StatusPermanentRedirect = 308 // RFC 7538, 3 StatusBadRequest = 400 // RFC 7231, 6.5.1 StatusPaymentRequired = 402 // RFC 7231, 6.5.2 StatusForbidden = 403 // RFC 7231, 6.5.3 StatusNotFound = 404 // RFC 7231, 6.5.4 StatusMethodNotAllowed = 405 // RFC 7231, 6.5.5 StatusNotAcceptable = 406 // RFC 7231, 6.5.6 StatusProxyAuthRequired = 407 // RFC 7235, 3.2 StatusRequestTimeout = 408 // RFC 7231, 6.5.7 StatusConflict = 409 // RFC 7231, 6.5.8 StatusGone = 410 // RFC 7231, 6.5.9 StatusLengthRequired = 411 // RFC 7231, 6.5.10 StatusPreconditionFailed = 412 // RFC 7232, 4.2 StatusRequestEntityTooLarge = 413 // RFC 7231, 6.5.11 StatusRequestURITooLong = 414 // RFC 7231, 6.5.12 StatusUnsupportedMediaType = 415 // RFC 7231, 6.5.13 StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4 StatusExpectationFailed = 417 // RFC 7231, 6.5.14 StatusTeapot = 418 // RFC 7168, 2.3.3 StatusUnprocessableEntity = 422 // RFC 4918, 11.2 StatusLocked = 423 // RFC 4918, 11.3 StatusFailedDependency = 424 // RFC 4918, 11.4 StatusUpgradeRequired = 426 // RFC 7231, 6.5.15 StatusPreconditionRequired = 428 // RFC 6585, 3 StatusTooManyRequests = 429 // RFC 6585, 4 StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5 StatusInternalServerError = 500 // RFC 7231, 6.6.1 StatusNotImplemented = 501 // RFC 7231, 6.6.2 StatusBadGateway = 502 // RFC 7231, 6.6.3 StatusGatewayTimeout = 504 // RFC 7231, 6.6.5 StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6 StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1 StatusInsufficientStorage = 507 // RFC 4918, 11.5 StatusLoopDetected = 508 // RFC 5842, 7.2 StatusNotExtended = 510 // RFC 2774, 7 StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6 )
HTTP status codes as registered with IANA. See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
const (
// Version is current version num
Version = "2.0"
)
Variables ¶
This section is empty.
Functions ¶
func CleanPath ¶
CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.
The following rules are applied iteratively until no further processing can be done:
- Replace multiple slashes with a single slash.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.
If the result of this process is an empty string, "/" is returned
func SetLogLevel ¶
func SetLogLevel(level string)
SetLogLevel support panic fatal error warn, warning info debug
func StatusText ¶
StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.
Types ¶
type Context ¶
type Context struct { Req *http.Request Rw http.ResponseWriter context.Context // contains filtered or unexported fields }
Context warps request and response writer
func (*Context) GetValue ¶
func (ctx *Context) GetValue(key interface{}) interface{}
GetValue of key
func (*Context) LogError ¶
func (ctx *Context) LogError(args ...interface{})
LogError print error level log with fields
func (*Context) LogInfo ¶
func (ctx *Context) LogInfo(args ...interface{})
LogInfo print info level log with fields
func (*Context) ParseValidateForm ¶
ParseValidateForm will parse request's form and map into a interface{} value
func (*Context) SetValue ¶
func (ctx *Context) SetValue(key, val interface{})
SetValue set value on context
func (*Context) WithCancel ¶
func (ctx *Context) WithCancel() (Context, context.CancelFunc)
WithCancel ...
func (*Context) WithDeadline ¶
WithDeadline ...
func (*Context) WriteData ¶
WriteData writes some data into the body stream and updates the HTTP code.
func (*Context) WriteHeader ¶
WriteHeader set response header
func (*Context) WriteStatus ¶
WriteStatus set response's status code
func (*Context) WriteString ¶
WriteString write raw string
type HandlerFunc ¶
type HandlerFunc func(Context)
HandlerFunc is a type alias for handler
func WrapF ¶
func WrapF(h http.HandlerFunc) HandlerFunc
WrapF wrap a http handlerfunc into HandlerFunc
func (HandlerFunc) ServeHTTP ¶
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP calls f(w, r).
type Middleware ¶
type Middleware func(HandlerFunc) HandlerFunc
Middleware accept a HandlerFunc and return another HandlerFunc
func WrapStdMiddleware ¶
func WrapStdMiddleware(middleware func(http.HandlerFunc) http.HandlerFunc) Middleware
WrapStdMiddleware add support for 3rd party http middleware
type Middlewares ¶
type Middlewares []Middleware
Middlewares contains list of Middleware
func (Middlewares) Wrap ¶
func (m Middlewares) Wrap(h HandlerFunc) HandlerFunc
Wrap middlewares into HandlerFunc
type Option ¶
type Option func(*Server)
Option use to customize Server
func SetHandleMethodNotAllowed ¶
SetHandleMethodNotAllowed return Option for set HandleMethodNotAllowed
func SetHandleOPTIONS ¶
SetHandleOPTIONS return Option for set HandleOPTIONS
func SetReadHeaderTimeout ¶
SetReadHeaderTimeout return Option for set read header timeout
func SetReadTimeout ¶
SetReadTimeout return Option for set read timeout
func SetRedirectFixedPath ¶
SetRedirectFixedPath return Option for set RedirectFixedPath
func SetRedirectTrailingSlash ¶
SetRedirectTrailingSlash return Option for set RedirectTrailingSlash
func SetWriteTimeout ¶
SetWriteTimeout return Option for set write timeout
type Params ¶
type Params []Param
Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.
type Router ¶
type Router interface { // Route set handler for given pattern and method Route(method string, path string, handler HandlerFunc) // Get adds a new Route for GET requests. Get(path string, handler HandlerFunc) // Post adds a new Route for POST requests. Post(path string, handler HandlerFunc) // Put adds a new Route for PUT requests. Put(path string, handler HandlerFunc) // Delete adds a new Route for DELETE requests. Delete(path string, handler HandlerFunc) // Patch adds a new Route for PATCH requests. Patch(path string, handler HandlerFunc) // Head adds a new Route for HEAD requests. Head(path string, handler HandlerFunc) // Options adds a new Route for OPTIONS requests. Options(path string, handler HandlerFunc) // Connect adds a new Route for CONNECT requests. Connect(path string, handler HandlerFunc) // Trace adds a new Route for TRACE requests. Trace(path string, handler HandlerFunc) // Any adds new Route for ALL method requests. Any(path string, handler HandlerFunc) // AddInterceptor add a interceptor for given path AddInterceptor(handler Middleware) }
Router ...
type Server ¶
type Server struct { // Router Router // Enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for GET requests // and 307 for all other request methods. RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for GET requests and 307 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // If enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // If enabled, the router automatically replies to OPTIONS requests. // Custom OPTIONS handlers take priority over automatic replies. HandleOPTIONS bool // timeout config ReadTimeout time.Duration WriteTimeout time.Duration ReadHeaderTimeout time.Duration ShutdownDuration time.Duration // contains filtered or unexported fields }
Server struct
func (*Server) AddInterceptor ¶
func (s *Server) AddInterceptor(handler Middleware)
AddInterceptor add a global interceptor
func (*Server) Group ¶
func (s *Server) Group(base string, interceptors ...Middleware) Router
Group create a group router with base url and shared interceptors
func (*Server) HandleNotAllowed ¶
func (s *Server) HandleNotAllowed(handler HandlerFunc)
HandleNotAllowed set server's methodNotAllowed
func (*Server) HandleNotFound ¶
func (s *Server) HandleNotFound(handler HandlerFunc)
HandleNotFound set server's notFoundHandler
func (*Server) Lookup ¶
func (s *Server) Lookup(method, path string) (HandlerFunc, Params, bool)
Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handle function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.