kratos: github.com/bilibili/kratos/pkg/net/http/blademaster Index | Files | Directories

package blademaster

import "github.com/bilibili/kratos/pkg/net/http/blademaster"

Index

Package Files

client.go context.go cors.go criticality.go csrf.go logger.go metadata.go metrics.go perf.go prometheus.go ratelimit.go recovery.go routergroup.go server.go trace.go tree.go utils.go

type CORSConfig Uses

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 Uses

func (c *CORSConfig) Validate() error

Validate is check configuration of user defined.

type Client Uses

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

Client is http client.

func NewClient Uses

func NewClient(c *ClientConfig) *Client

NewClient new a http client.

func (*Client) Do Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func (client *Client) SetConfig(c *ClientConfig)

SetConfig set client config.

func (*Client) SetTransport Uses

func (client *Client) SetTransport(t xhttp.RoundTripper)

SetTransport set client transport

type ClientConfig Uses

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 Uses

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 Uses

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 Uses

func (c *Context) AbortWithStatus(code int)

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 Uses

func (c *Context) Bind(obj interface{}) error

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) BindWith Uses

func (c *Context) BindWith(obj interface{}, b binding.Binding) error

BindWith bind req arg with parser.

func (*Context) Bytes Uses

func (c *Context) Bytes(code int, contentType string, data ...[]byte)

Bytes writes some data into the body stream and updates the HTTP code.

func (*Context) Get Uses

func (c *Context) Get(key string) (value interface{}, exists bool)

Get returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)

func (*Context) IsAborted Uses

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) JSON Uses

func (c *Context) JSON(data interface{}, err error)

JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".

func (*Context) JSONMap Uses

func (c *Context) JSONMap(data map[string]interface{}, err error)

JSONMap serializes the given map as map JSON into the response body. It also sets the Content-Type as "application/json".

func (*Context) Next Uses

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 Uses

func (c *Context) Protobuf(data proto.Message, err error)

Protobuf serializes the given struct as PB into the response body. It also sets the ContentType as "application/x-protobuf".

func (*Context) Redirect Uses

func (c *Context) Redirect(code int, location string)

Redirect returns a HTTP redirect to the specific location.

func (*Context) Render Uses

func (c *Context) Render(code int, r render.Render)

Render http response with http code by a render instance.

func (*Context) Set Uses

func (c *Context) Set(key string, value interface{})

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.

func (*Context) Status Uses

func (c *Context) Status(code int)

Status sets the HTTP response code.

func (*Context) String Uses

func (c *Context) String(code int, format string, values ...interface{})

String writes the given string into the response body.

func (*Context) XML Uses

func (c *Context) XML(data interface{}, err error)

XML serializes the given struct as XML into the response body. It also sets the Content-Type as "application/xml".

type Engine Uses

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 Uses

func DefaultServer(conf *ServerConfig) *Engine

DefaultServer returns an Engine instance with the Recovery and Logger middleware already attached.

func NewServer Uses

func NewServer(conf *ServerConfig) *Engine

NewServer returns a new blank Engine instance without any middleware attached.

func (*Engine) Inject Uses

func (engine *Engine) Inject(pattern string, handlers ...HandlerFunc)

Inject is

func (*Engine) NoMethod Uses

func (engine *Engine) NoMethod(handlers ...HandlerFunc)

NoMethod sets the handlers called when... TODO.

func (*Engine) NoRoute Uses

func (engine *Engine) NoRoute(handlers ...HandlerFunc)

NoRoute adds handlers for NoRoute. It return a 404 code by default.

func (*Engine) Ping Uses

func (engine *Engine) Ping(handler HandlerFunc)

Ping is used to set the general HTTP ping handler.

func (*Engine) Register Uses

func (engine *Engine) Register(handler HandlerFunc)

Register is used to export metadata to discovery.

func (*Engine) Router Uses

func (engine *Engine) Router() http.Handler

Router return a http.Handler for using http.ListenAndServe() directly.

func (*Engine) Run Uses

func (engine *Engine) Run(addr ...string) (err error)

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 Uses

func (engine *Engine) RunServer(server *http.Server, l net.Listener) (err error)

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 Uses

func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error)

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 Uses

func (engine *Engine) RunUnix(file string) (err error)

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 Uses

func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP conforms to the http.Handler interface.

func (*Engine) Server Uses

func (engine *Engine) Server() *http.Server

Server is used to load stored http server.

func (*Engine) SetConfig Uses

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 Uses

func (engine *Engine) SetMethodConfig(path string, mc *MethodConfig)

SetMethodConfig is used to set config on specified path

func (*Engine) Shutdown Uses

func (engine *Engine) Shutdown(ctx context.Context) error

Shutdown the http server without interrupting active connections.

func (*Engine) Start Uses

func (engine *Engine) Start() error

Start listen and serve bm engine by given DSN.

func (*Engine) Use Uses

func (engine *Engine) Use(middleware ...Handler) IRoutes

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 Uses

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 Uses

type Handler interface {
    ServeHTTP(c *Context)
}

Handler responds to an HTTP request.

type HandlerFunc Uses

type HandlerFunc func(*Context)

HandlerFunc http request handler function.

func CORS Uses

func CORS(allowOriginHosts []string) HandlerFunc

CORS returns the location middleware with default configuration.

func CSRF Uses

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 Uses

func Criticality(pathCriticality criticalityPkg.Criticality) HandlerFunc

Criticality is

func Logger Uses

func Logger() HandlerFunc

Logger is logger middleware

func Recovery Uses

func Recovery() HandlerFunc

Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.

func Trace Uses

func Trace() HandlerFunc

Trace is trace middleware

func (HandlerFunc) ServeHTTP Uses

func (f HandlerFunc) ServeHTTP(c *Context)

ServeHTTP calls f(ctx).

type IRouter Uses

type IRouter interface {
    IRoutes
    Group(string, ...HandlerFunc) *RouterGroup
}

IRouter http router framework interface.

type IRoutes Uses

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 MethodConfig Uses

type MethodConfig struct {
    Timeout xtime.Duration
}

MethodConfig is

type Param Uses

type Param struct {
    Key   string
    Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params Uses

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.

func (Params) ByName Uses

func (ps Params) ByName(name string) (va string)

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

func (Params) Get Uses

func (ps Params) Get(name string) (string, bool)

Get returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

type RateLimiter Uses

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

RateLimiter bbr middleware.

func NewRateLimiter Uses

func NewRateLimiter(conf *bbr.Config) (s *RateLimiter)

NewRateLimiter return a ratelimit middleware.

func (*RateLimiter) Limit Uses

func (b *RateLimiter) Limit() HandlerFunc

Limit return a bm handler func.

type RouterGroup Uses

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 Uses

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 Uses

func (group *RouterGroup) BasePath() string

BasePath router group base path.

func (*RouterGroup) DELETE Uses

func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes

DELETE is a shortcut for router.Handle("DELETE", path, handle).

func (*RouterGroup) GET Uses

func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes

GET is a shortcut for router.Handle("GET", path, handle).

func (*RouterGroup) Group Uses

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 Uses

func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes

HEAD is a shortcut for router.Handle("HEAD", path, handle).

func (*RouterGroup) Handle Uses

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 Uses

func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes

OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle).

func (*RouterGroup) PATCH Uses

func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes

PATCH is a shortcut for router.Handle("PATCH", path, handle).

func (*RouterGroup) POST Uses

func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes

POST is a shortcut for router.Handle("POST", path, handle).

func (*RouterGroup) PUT Uses

func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes

PUT is a shortcut for router.Handle("PUT", path, handle).

func (*RouterGroup) SetMethodConfig Uses

func (group *RouterGroup) SetMethodConfig(config *MethodConfig) *RouterGroup

SetMethodConfig is used to set config on specified method

func (*RouterGroup) Use Uses

func (group *RouterGroup) Use(middleware ...Handler) IRoutes

Use adds middleware to the group, see example code in doc.

func (*RouterGroup) UseFunc Uses

func (group *RouterGroup) UseFunc(middleware ...HandlerFunc) IRoutes

UseFunc adds middleware to the group, see example code in doc.

type ServerConfig Uses

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 Uses

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 Uses

func NewTraceTransport(rt http.RoundTripper, peerService string, internalTags ...trace.Tag) *TraceTransport

NewTraceTransport NewTraceTransport

func (*TraceTransport) RoundTrip Uses

func (t *TraceTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements the RoundTripper interface

Directories

PathSynopsis
binding
binding/examplePackage example is a generated protocol buffer package.
renderPackage render is a generated protocol buffer package.

Package blademaster imports 44 packages (graph) and is imported by 6 packages. Updated 2019-10-28. Refresh now. Tools for package owners.