Documentation ¶
Overview ¶
Copyright 2017 Manu Martinez-Almeida. All rights reserved. Use of this source code is governed by a MIT style license that can be found in the LICENSE file.
Index ¶
- func Dir(root string, listDirectory bool) http.FileSystem
- type CORSConfig
- type Client
- func (client *Client) Do(c context.Context, req *xhttp.Request, res interface{}, v ...string) (err error)
- func (client *Client) Get(c context.Context, uri, ip string, params url.Values, res interface{}) (err error)
- func (client *Client) JSON(c context.Context, req *xhttp.Request, res interface{}, v ...string) (err error)
- func (client *Client) NewRequest(method, uri, realIP string, params url.Values) (req *xhttp.Request, err error)
- func (client *Client) PB(c context.Context, req *xhttp.Request, res proto.Message, v ...string) (err error)
- func (client *Client) Post(c context.Context, uri, ip string, params url.Values, res interface{}) (err error)
- func (client *Client) RESTfulGet(c context.Context, uri, ip string, params url.Values, res interface{}, ...) (err error)
- func (client *Client) RESTfulPost(c context.Context, uri, ip string, params url.Values, res interface{}, ...) (err error)
- func (client *Client) Raw(c context.Context, req *xhttp.Request, v ...string) (bs []byte, err error)
- func (client *Client) SetConfig(c *ClientConfig)
- func (client *Client) SetTransport(t xhttp.RoundTripper)
- type ClientConfig
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortWithStatus(code int)
- func (c *Context) Bind(obj interface{}) error
- func (c *Context) BindWith(obj interface{}, b binding.Binding) error
- func (c *Context) Bytes(code int, contentType string, data ...[]byte)
- func (c *Context) Get(key string) (value interface{}, exists bool)
- func (c *Context) Header(key, value string)
- func (c *Context) IsAborted() bool
- func (c *Context) JSON(data interface{}, err error)
- func (c *Context) JSONMap(data map[string]interface{}, err error)
- func (c *Context) Next()
- func (c *Context) Protobuf(data proto.Message, err error)
- func (c *Context) Redirect(code int, location string)
- func (c *Context) Render(code int, r render.Render)
- func (c *Context) Set(key string, value interface{})
- func (c *Context) Status(code int)
- func (c *Context) String(code int, format string, values ...interface{})
- func (c *Context) XML(data interface{}, err error)
- type Engine
- func (engine *Engine) Inject(pattern string, handlers ...HandlerFunc)
- func (engine *Engine) NoMethod(handlers ...HandlerFunc)
- func (engine *Engine) NoRoute(handlers ...HandlerFunc)
- func (engine *Engine) Ping(handler HandlerFunc)
- func (engine *Engine) Register(handler HandlerFunc)
- func (engine *Engine) Router() http.Handler
- func (engine *Engine) Run(addr ...string) (err error)
- func (engine *Engine) RunServer(server *http.Server, l net.Listener) (err error)
- func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error)
- func (engine *Engine) RunUnix(file string) (err error)
- func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (engine *Engine) Server() *http.Server
- func (engine *Engine) SetConfig(conf *ServerConfig) (err error)
- func (engine *Engine) SetMethodConfig(path string, mc *MethodConfig)
- func (engine *Engine) Shutdown(ctx context.Context) error
- func (engine *Engine) Start() error
- func (engine *Engine) Use(middleware ...Handler) IRoutes
- func (engine *Engine) UseFunc(middleware ...HandlerFunc) IRoutes
- type Handler
- type HandlerFunc
- type IRouter
- type IRoutes
- type MethodConfig
- type Param
- type Params
- type RateLimiter
- type RouterGroup
- func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) BasePath() string
- func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes
- func (group *RouterGroup) SetMethodConfig(config *MethodConfig) *RouterGroup
- func (group *RouterGroup) Static(relativePath, root string) IRoutes
- func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes
- func (group *RouterGroup) Use(middleware ...Handler) IRoutes
- func (group *RouterGroup) UseFunc(middleware ...HandlerFunc) IRoutes
- type ServerConfig
- type TraceTransport
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Dir ¶ added in v0.3.11
func Dir(root string, listDirectory bool) http.FileSystem
Dir returns a http.Filesystem that can be used by http.FileServer(). It is used internally in router.Static(). if listDirectory == true, then it works the same as http.Dir() otherwise it returns a filesystem that prevents http.FileServer() to list the directory files.
Types ¶
type CORSConfig ¶
type CORSConfig struct { AllowAllOrigins bool // AllowedOrigins is a list of origins a cross-domain request can be executed from. // If the special "*" value is present in the list, all origins will be allowed. // Default value is [] AllowOrigins []string // AllowOriginFunc is a custom function to validate the origin. It take the origin // as argument and returns true if allowed or false otherwise. If this option is // set, the content of AllowedOrigins is ignored. AllowOriginFunc func(origin string) bool // AllowedMethods is a list of methods the client is allowed to use with // cross-domain requests. Default value is simple methods (GET and POST) AllowMethods []string // AllowedHeaders is list of non simple headers the client is allowed to use with // cross-domain requests. AllowHeaders []string // AllowCredentials indicates whether the request can include user credentials like // cookies, HTTP authentication or client side SSL certificates. AllowCredentials bool // ExposedHeaders indicates which headers are safe to expose to the API of a CORS // API specification ExposeHeaders []string // MaxAge indicates how long (in seconds) the results of a preflight request // can be cached MaxAge time.Duration }
CORSConfig represents all available options for the middleware.
func (*CORSConfig) Validate ¶
func (c *CORSConfig) Validate() error
Validate is check configuration of user defined.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is http client.
func (*Client) Do ¶
func (client *Client) Do(c context.Context, req *xhttp.Request, res interface{}, v ...string) (err error)
Do sends an HTTP request and returns an HTTP json response.
func (*Client) Get ¶
func (client *Client) Get(c context.Context, uri, ip string, params url.Values, res interface{}) (err error)
Get issues a GET to the specified URL.
func (*Client) JSON ¶
func (client *Client) JSON(c context.Context, req *xhttp.Request, res interface{}, v ...string) (err error)
JSON sends an HTTP request and returns an HTTP json response.
func (*Client) NewRequest ¶
func (client *Client) NewRequest(method, uri, realIP string, params url.Values) (req *xhttp.Request, err error)
NewRequest new http request with method, uri, ip, values and headers. TODO(zhoujiahui): param realIP should be removed later.
func (*Client) PB ¶
func (client *Client) PB(c context.Context, req *xhttp.Request, res proto.Message, v ...string) (err error)
PB sends an HTTP request and returns an HTTP proto response.
func (*Client) Post ¶
func (client *Client) Post(c context.Context, uri, ip string, params url.Values, res interface{}) (err error)
Post issues a Post to the specified URL.
func (*Client) RESTfulGet ¶
func (client *Client) RESTfulGet(c context.Context, uri, ip string, params url.Values, res interface{}, v ...interface{}) (err error)
RESTfulGet issues a RESTful GET to the specified URL.
func (*Client) RESTfulPost ¶
func (client *Client) RESTfulPost(c context.Context, uri, ip string, params url.Values, res interface{}, v ...interface{}) (err error)
RESTfulPost issues a RESTful Post to the specified URL.
func (*Client) Raw ¶
func (client *Client) Raw(c context.Context, req *xhttp.Request, v ...string) (bs []byte, err error)
Raw sends an HTTP request and returns bytes response
func (*Client) SetConfig ¶
func (client *Client) SetConfig(c *ClientConfig)
SetConfig set client config.
func (*Client) SetTransport ¶
func (client *Client) SetTransport(t xhttp.RoundTripper)
SetTransport set client transport
type ClientConfig ¶
type ClientConfig struct { Dial xtime.Duration Timeout xtime.Duration KeepAlive xtime.Duration Breaker *breaker.Config URL map[string]*ClientConfig Host map[string]*ClientConfig }
ClientConfig is http client conf.
type Context ¶
type Context struct { context.Context Request *http.Request Writer http.ResponseWriter // Keys is a key/value pair exclusively for the context of each request. Keys map[string]interface{} Error error RoutePath string Params Params // contains filtered or unexported fields }
Context is the most important part. It allows us to pass variables between middleware, manage the flow, validate the JSON of a request and render a JSON response for example.
func (*Context) Abort ¶
func (c *Context) Abort()
Abort prevents pending handlers from being called. Note that this will not stop the current handler. Let's say you have an authorization middleware that validates that the current request is authorized. If the authorization fails (ex: the password does not match), call Abort to ensure the remaining handlers for this request are not called.
func (*Context) AbortWithStatus ¶
AbortWithStatus calls `Abort()` and writes the headers with the specified status code. For example, a failed attempt to authenticate a request could use: context.AbortWithStatus(401).
func (*Context) Bind ¶
Bind checks the Content-Type to select a binding engine automatically, Depending the "Content-Type" header different bindings are used:
"application/json" --> JSON binding "application/xml" --> XML binding
otherwise --> returns an error. It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input. It decodes the json payload into the struct specified as a pointer. It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.
func (*Context) Get ¶
Get returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)
func (*Context) JSON ¶
JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".
func (*Context) JSONMap ¶
JSONMap serializes the given map as map JSON into the response body. It also sets the Content-Type as "application/json".
func (*Context) Next ¶
func (c *Context) Next()
Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler. See example in godoc.
func (*Context) Protobuf ¶
Protobuf serializes the given struct as PB into the response body. It also sets the ContentType as "application/x-protobuf".
func (*Context) Set ¶
Set is used to store a new key/value pair exclusively for this context. It also lazy initializes c.Keys if it was not used previously.
type Engine ¶
type Engine struct { RouterGroup // If enabled, the url.RawPath will be used to find parameters. UseRawPath bool // If true, the path value will be unescaped. // If UseRawPath is false (by default), the UnescapePathValues effectively is true, // as url.Path gonna be used, which is already unescaped. UnescapePathValues 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 // contains filtered or unexported fields }
Engine is the framework's instance, it contains the muxer, middleware and configuration settings. Create an instance of Engine, by using New() or Default()
func DefaultServer ¶
func DefaultServer(conf *ServerConfig) *Engine
DefaultServer returns an Engine instance with the Recovery and Logger middleware already attached.
func NewServer ¶
func NewServer(conf *ServerConfig) *Engine
NewServer returns a new blank Engine instance without any middleware attached.
func (*Engine) Inject ¶
func (engine *Engine) Inject(pattern string, handlers ...HandlerFunc)
Inject is
func (*Engine) NoMethod ¶
func (engine *Engine) NoMethod(handlers ...HandlerFunc)
NoMethod sets the handlers called when... TODO.
func (*Engine) NoRoute ¶
func (engine *Engine) NoRoute(handlers ...HandlerFunc)
NoRoute adds handlers for NoRoute. It return a 404 code by default.
func (*Engine) Ping ¶
func (engine *Engine) Ping(handler HandlerFunc)
Ping is used to set the general HTTP ping handler.
func (*Engine) Register ¶
func (engine *Engine) Register(handler HandlerFunc)
Register is used to export metadata to discovery.
func (*Engine) Run ¶
Run attaches the router to a http.Server and starts listening and serving HTTP requests. It is a shortcut for http.ListenAndServe(addr, router) Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) RunServer ¶
RunServer will serve and start listening HTTP requests by given server and listener. Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) RunTLS ¶
RunTLS attaches the router to a http.Server and starts listening and serving HTTPS (secure) requests. It is a shortcut for http.ListenAndServeTLS(addr, certFile, keyFile, router) Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) RunUnix ¶
RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests through the specified unix socket (ie. a file). Note: this method will block the calling goroutine indefinitely unless an error happens.
func (*Engine) ServeHTTP ¶
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP conforms to the http.Handler interface.
func (*Engine) SetConfig ¶
func (engine *Engine) SetConfig(conf *ServerConfig) (err error)
SetConfig is used to set the engine configuration. Only the valid config will be loaded.
func (*Engine) SetMethodConfig ¶
func (engine *Engine) SetMethodConfig(path string, mc *MethodConfig)
SetMethodConfig is used to set config on specified path
func (*Engine) Use ¶
Use attachs a global middleware to the router. ie. the middleware attached though Use() will be included in the handlers chain for every single request. Even 404, 405, static files... For example, this is the right place for a logger or error management middleware.
func (*Engine) UseFunc ¶
func (engine *Engine) UseFunc(middleware ...HandlerFunc) IRoutes
UseFunc attachs a global middleware to the router. ie. the middleware attached though UseFunc() will be included in the handlers chain for every single request. Even 404, 405, static files... For example, this is the right place for a logger or error management middleware.
type Handler ¶
type Handler interface {
ServeHTTP(c *Context)
}
Handler responds to an HTTP request.
type HandlerFunc ¶
type HandlerFunc func(*Context)
HandlerFunc http request handler function.
func CORS ¶
func CORS(allowOriginHosts []string) HandlerFunc
CORS returns the location middleware with default configuration.
func CSRF ¶
func CSRF(allowHosts []string, allowPattern []string) HandlerFunc
CSRF returns the csrf middleware to prevent invalid cross site request. Only referer is checked currently.
func Criticality ¶
func Criticality(pathCriticality criticalityPkg.Criticality) HandlerFunc
Criticality is
func Recovery ¶
func Recovery() HandlerFunc
Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
type IRouter ¶
type IRouter interface { IRoutes Group(string, ...HandlerFunc) *RouterGroup }
IRouter http router framework interface.
type IRoutes ¶
type IRoutes interface { UseFunc(...HandlerFunc) IRoutes Use(...Handler) IRoutes Handle(string, string, ...HandlerFunc) IRoutes HEAD(string, ...HandlerFunc) IRoutes GET(string, ...HandlerFunc) IRoutes POST(string, ...HandlerFunc) IRoutes PUT(string, ...HandlerFunc) IRoutes DELETE(string, ...HandlerFunc) IRoutes }
IRoutes http router interface.
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 RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter bbr middleware.
func NewRateLimiter ¶
func NewRateLimiter(conf *bbr.Config) (s *RateLimiter)
NewRateLimiter return a ratelimit middleware.
func (*RateLimiter) Limit ¶
func (b *RateLimiter) Limit() HandlerFunc
Limit return a bm handler func.
type RouterGroup ¶
type RouterGroup struct { Handlers []HandlerFunc // contains filtered or unexported fields }
RouterGroup is used internally to configure router, a RouterGroup is associated with a prefix and an array of handlers (middleware).
func (*RouterGroup) Any ¶
func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes
Any registers a route that matches all the HTTP methods. GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.
func (*RouterGroup) BasePath ¶
func (group *RouterGroup) BasePath() string
BasePath router group base path.
func (*RouterGroup) DELETE ¶
func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes
DELETE is a shortcut for router.Handle("DELETE", path, handle).
func (*RouterGroup) GET ¶
func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes
GET is a shortcut for router.Handle("GET", path, handle).
func (*RouterGroup) Group ¶
func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup
Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix. For example, all the routes that use a common middlware for authorization could be grouped.
func (*RouterGroup) HEAD ¶
func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes
HEAD is a shortcut for router.Handle("HEAD", path, handle).
func (*RouterGroup) Handle ¶
func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes
Handle registers a new request handle and middleware with the given path and method. The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes. See the example code in doc.
For HEAD, GET, POST, PUT, and DELETE requests the respective shortcut functions can be used.
This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).
func (*RouterGroup) OPTIONS ¶
func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes
OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle).
func (*RouterGroup) PATCH ¶
func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes
PATCH is a shortcut for router.Handle("PATCH", path, handle).
func (*RouterGroup) POST ¶
func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes
POST is a shortcut for router.Handle("POST", path, handle).
func (*RouterGroup) PUT ¶
func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes
PUT is a shortcut for router.Handle("PUT", path, handle).
func (*RouterGroup) SetMethodConfig ¶
func (group *RouterGroup) SetMethodConfig(config *MethodConfig) *RouterGroup
SetMethodConfig is used to set config on specified method
func (*RouterGroup) Static ¶ added in v0.3.11
func (group *RouterGroup) Static(relativePath, root string) IRoutes
Static serves files from the given file system root. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use :
router.Static("/static", "/var/www")
func (*RouterGroup) StaticFS ¶ added in v0.3.11
func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes
StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. Gin by default user: gin.Dir()
func (*RouterGroup) Use ¶
func (group *RouterGroup) Use(middleware ...Handler) IRoutes
Use adds middleware to the group, see example code in doc.
func (*RouterGroup) UseFunc ¶
func (group *RouterGroup) UseFunc(middleware ...HandlerFunc) IRoutes
UseFunc adds middleware to the group, see example code in doc.
type ServerConfig ¶
type ServerConfig struct { Network string `dsn:"network"` Addr string `dsn:"address"` Timeout xtime.Duration `dsn:"query.timeout"` ReadTimeout xtime.Duration `dsn:"query.readTimeout"` WriteTimeout xtime.Duration `dsn:"query.writeTimeout"` }
ServerConfig is the bm server config model
type TraceTransport ¶
type TraceTransport struct { // The actual RoundTripper to use for the request. A nil // RoundTripper defaults to http.DefaultTransport. http.RoundTripper // contains filtered or unexported fields }
TraceTransport wraps a RoundTripper. If a request is being traced with Tracer, Transport will inject the current span into the headers, and set HTTP related tags on the span.
func NewTraceTransport ¶
func NewTraceTransport(rt http.RoundTripper, peerService string, internalTags ...trace.Tag) *TraceTransport
NewTraceTransport NewTraceTransport