gin

package
v0.4.5 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2020 License: MIT Imports: 44 Imported by: 0

README

net/http/gin

项目简介

http 框架,带来如飞一般的体验。

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func Dir

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 NewClient

func NewClient(c *ClientConfig) *Client

NewClient new a 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

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

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

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

BindWith bind req arg with parser.

func (*Context) Bytes

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) DefaultQuery added in v0.4.5

func (c *Context) DefaultQuery(key, defaultValue string) string

DefaultQuery returns the keyed url query value if it exists, otherwise it returns the specified defaultValue string. See: Query() and GetQuery() for further information.

GET /?name=Manu&lastname=
c.DefaultQuery("name", "unknown") == "Manu"
c.DefaultQuery("id", "none") == "none"
c.DefaultQuery("lastname", "none") == ""

func (*Context) File added in v0.4.4

func (c *Context) File(filepath string)

File writes the specified file into the body stream in a efficient way.

func (*Context) Get

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) GetQuery added in v0.4.5

func (c *Context) GetQuery(key string) (string, bool)

GetQuery is like Query(), it returns the keyed url query value if it exists `(value, true)` (even when the value is an empty string), otherwise it returns `("", false)`. It is shortcut for `c.Request.URL.Query().Get(key)`

GET /?name=Manu&lastname=
("Manu", true) == c.GetQuery("name")
("", false) == c.GetQuery("id")
("", true) == c.GetQuery("lastname")

func (*Context) GetQueryArray added in v0.4.5

func (c *Context) GetQueryArray(key string) ([]string, bool)

GetQueryArray returns a slice of strings for a given query key, plus a boolean value whether at least one value exists for the given key.

func (*Context) GetQueryMap added in v0.4.5

func (c *Context) GetQueryMap(key string) (map[string]string, bool)

GetQueryMap returns a map for a given query key, plus a boolean value whether at least one value exists for the given key.

func (*Context) Header

func (c *Context) Header(key, value string)

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) JSON

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

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

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

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) Query added in v0.4.5

func (c *Context) Query(key string) string

Query returns the keyed url query value if it exists, otherwise it returns an empty string `("")`. It is shortcut for `c.Request.URL.Query().Get(key)`

    GET /path?id=1234&name=Manu&value=
	   c.Query("id") == "1234"
	   c.Query("name") == "Manu"
	   c.Query("value") == ""
	   c.Query("wtf") == ""

func (*Context) QueryArray added in v0.4.5

func (c *Context) QueryArray(key string) []string

QueryArray returns a slice of strings for a given query key. The length of the slice depends on the number of params with the given key.

func (*Context) QueryMap added in v0.4.5

func (c *Context) QueryMap(key string) map[string]string

QueryMap returns a map for a given query key.

func (*Context) Redirect

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

Redirect returns a HTTP redirect to the specific location.

func (*Context) Render

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

Render http response with http code by a render instance.

func (*Context) Set

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

func (c *Context) Status(code int)

Status sets the HTTP response code.

func (*Context) String

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

String writes the given string into the response body.

func (*Context) XML

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

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) Router

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

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

func (*Engine) Run

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

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

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

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

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

ServeHTTP conforms to the http.Handler interface.

func (*Engine) Server

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

Server is used to load stored http server.

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) Shutdown

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

Shutdown the http server without interrupting active connections.

func (*Engine) Start

func (engine *Engine) Start() error

Start listen and serve bm engine by given DSN.

func (*Engine) Use

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

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 Logger

func Logger() HandlerFunc

Logger is logger middleware

func Recovery

func Recovery() HandlerFunc

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

func Trace

func Trace() HandlerFunc

Trace is trace middleware

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(c *Context)

ServeHTTP calls f(ctx).

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 MethodConfig

type MethodConfig struct {
	Timeout xtime.Duration
}

MethodConfig is

type Param

type Param struct {
	Key   string
	Value string
}

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

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.

func (Params) ByName

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

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

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

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

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

func (*TraceTransport) RoundTrip

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

RoundTrip implements the RoundTripper interface

Directories

Path Synopsis
example
Package example is a generated protocol buffer package.
Package example is a generated protocol buffer package.
Package render is a generated protocol buffer package.
Package render is a generated protocol buffer package.

Jump to

Keyboard shortcuts

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