dispatcher

package
v0.13.6-0...-d3ad96a Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2020 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Marshal is exported by gin/json package.
	Marshal = json.Marshal
	// Unmarshal is exported by gin/json package.
	Unmarshal = json.Unmarshal
	// MarshalIndent is exported by gin/json package.
	MarshalIndent = json.MarshalIndent
	// NewDecoder is exported by gin/json package.
	NewDecoder = json.NewDecoder
	// NewEncoder is exported by gin/json package.
	NewEncoder = json.NewEncoder
)

Functions

This section is empty.

Types

type Context

type Context struct {
	Writer  ResponseWriter
	Request IRequest
	Params  Params

	Keys     map[string]interface{}
	Errors   errorMsgs
	Accepted []string
	// contains filtered or unexported fields
}

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

func (c *Context) AbortWithError(code int, err error) *Error

AbortWithError calls `AbortWithStatus()` and `Error()` internally. This method stops the chain, writes the status code and pushes the specified error to `c.Errors`. See Context.Error() for more details.

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

func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{})

AbortWithStatusJSON calls `Abort()` and then `JSON` internally. This method stops the chain, writes the status code and return a JSON body. It also sets the Content-Type as "application/json".

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP 获取客户端IP

func (*Context) Copy

func (c *Context) Copy() *Context

Copy returns a copy of the current context that can be safely used outside the request's scope. This has to be used when the context has to be passed to a goroutine.

func (*Context) Data

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

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

func (*Context) DefaultPostForm

func (c *Context) DefaultPostForm(key, defaultValue string) interface{}

DefaultPostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns the specified defaultValue string. See: PostForm() and GetPostForm() for further information.

func (*Context) Error

func (c *Context) Error(err error) *Error

Error attaches an error to the current context. The error is pushed to a list of errors. It's a good idea to call Error for each error that occurred during the resolution of a request. A middleware can be used to collect all the errors and push them to a database together, print a log, or append it in the HTTP response. Error will panic if err is nil.

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

func (c *Context) GetBool(key string) (b bool)

GetBool returns the value associated with the key as a boolean.

func (*Context) GetDuration

func (c *Context) GetDuration(key string) (d time.Duration)

GetDuration returns the value associated with the key as a duration.

func (*Context) GetFloat64

func (c *Context) GetFloat64(key string) (f64 float64)

GetFloat64 returns the value associated with the key as a float64.

func (*Context) GetHeader

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

GetHeader returns value from request headers.

func (*Context) GetInt

func (c *Context) GetInt(key string) (i int)

GetInt returns the value associated with the key as an integer.

func (*Context) GetInt64

func (c *Context) GetInt64(key string) (i64 int64)

GetInt64 returns the value associated with the key as an integer.

func (*Context) GetPostForm

func (c *Context) GetPostForm(key string) (interface{}, bool)

GetPostForm is like PostForm(key). It returns the specified key from a POST urlencoded form or multipart form when it exists `(value, true)` (even when the value is an empty string), otherwise it returns ("", false). For example, during a PATCH request to update the user's email:

    email=mail@example.com  -->  ("mail@example.com", true) := GetPostForm("email") // set email to "mail@example.com"
	   email=                  -->  ("", true) := GetPostForm("email") // set email to ""
                            -->  ("", false) := GetPostForm("email") // do nothing with email

func (*Context) GetRawData

func (c *Context) GetRawData() (interface{}, error)

GetRawData return stream data.

func (*Context) GetString

func (c *Context) GetString(key string) (s string)

GetString returns the value associated with the key as a string.

func (*Context) GetStringMap

func (c *Context) GetStringMap(key string) (sm map[string]interface{})

GetStringMap returns the value associated with the key as a map of interfaces.

func (*Context) GetStringMapString

func (c *Context) GetStringMapString(key string) (sms map[string]string)

GetStringMapString returns the value associated with the key as a map of strings.

func (*Context) GetStringMapStringSlice

func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)

GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.

func (*Context) GetStringSlice

func (c *Context) GetStringSlice(key string) (ss []string)

GetStringSlice returns the value associated with the key as a slice of strings.

func (*Context) GetTime

func (c *Context) GetTime(key string) (t time.Time)

GetTime returns the value associated with the key as time.

func (*Context) Header

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

Header is a intelligent shortcut for c.Writer.Header().Set(key, value). It writes a header in the response. If value == "", this method removes the header `c.Writer.Header().Del(key)`

func (*Context) IndentedJSON

func (c *Context) IndentedJSON(code int, obj interface{})

IndentedJSON serializes the given struct as pretty JSON (indented + endlines) into the response body. It also sets the Content-Type as "application/json". WARNING: we recommend to use this only for development purposes since printing pretty JSON is more CPU and bandwidth consuming. Use Context.JSON() instead.

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted returns true if the current context was aborted.

func (*Context) JSON

func (c *Context) JSON(code int, obj interface{})

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

func (*Context) MustGet

func (c *Context) MustGet(key string) interface{}

MustGet returns the value for the given key if it exists, otherwise it panics.

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 GitHub.

func (*Context) Param

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

Param returns the value of the URL param. It is a shortcut for c.Params.ByName(key)

router.GET("/user/:id", func(c *gin.Context) {
    // a GET request to /user/john
    id := c.Param("id") // id == "john"
})

func (*Context) PostForm

func (c *Context) PostForm(key string) interface{}

PostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns an empty string `("")`.

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)

func (*Context) SecureJSON

func (c *Context) SecureJSON(code int, obj interface{})

SecureJSON serializes the given struct as Secure JSON into the response body. Default prepends "while(1)," to response body if the given struct is array values. It also sets the Content-Type as "application/json".

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(code int, obj interface{})

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

func (*Context) YAML

func (c *Context) YAML(code int, obj interface{})

YAML serializes the given struct as YAML into the response body.

type Dispatcher

type Dispatcher struct {
	RouterGroup
	// contains filtered or unexported fields
}

func New

func New() *Dispatcher

func (*Dispatcher) Find

func (engine *Dispatcher) Find(path string) bool

Find 查找指定路由是否存在

func (*Dispatcher) HandleRequest

func (engine *Dispatcher) HandleRequest(r IRequest) (w *responseWriter, err error)

HandleRequest 处理外部请求

func (*Dispatcher) Routes

func (engine *Dispatcher) Routes() (routes RoutesInfo)

Routes returns a slice of registered routes, including some useful information, such as: the http method, path and the handler name.

func (*Dispatcher) Use

func (engine *Dispatcher) Use(middleware ...HandlerFunc) IRoutes

type Error

type Error struct {
	Err      error
	Type     ErrorType
	Metadata interface{}
}

func (Error) Error

func (msg Error) Error() string

Error implements the error interface

func (*Error) IsType

func (msg *Error) IsType(flags ErrorType) bool

func (*Error) JSON

func (msg *Error) JSON() interface{}

func (*Error) MarshalJSON

func (msg *Error) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface.

func (*Error) SetMetadata

func (msg *Error) SetMetadata(data interface{}) *Error

func (*Error) SetType

func (msg *Error) SetType(flags ErrorType) *Error

type ErrorType

type ErrorType uint64
const (
	ErrorTypeBind    ErrorType = 1 << 63 // used when c.Bind() fails
	ErrorTypeRender  ErrorType = 1 << 62 // used when c.Render() fails
	ErrorTypePrivate ErrorType = 1 << 0
	ErrorTypePublic  ErrorType = 1 << 1

	ErrorTypeAny ErrorType = 1<<64 - 1
	ErrorTypeNu            = 2
)

type H

type H map[string]interface{}

H is a shortcup for map[string]interface{}

func (H) MarshalXML

func (h H) MarshalXML(e *xml.Encoder, start xml.StartElement) error

MarshalXML allows type H to be used with xml.Marshal.

type HandlerFunc

type HandlerFunc func(*Context)

type HandlersChain

type HandlersChain []HandlerFunc

func (HandlersChain) Last

func (c HandlersChain) Last() HandlerFunc

Last returns the last handler in the chain. ie. the last handler is the main own.

type IRequest

type IRequest interface {
	GetService() string
	GetMethod() string
	GetForm() map[string]interface{}
	GetHeader() map[string]string
}

type IRouter

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

type IRoutes

type IRoutes interface {
	Use(...HandlerFunc) IRoutes
	Handle(string, string, ...HandlerFunc) IRoutes
	Any(string, ...HandlerFunc) IRoutes
	GET(string, ...HandlerFunc) IRoutes
	POST(string, ...HandlerFunc) IRoutes
	DELETE(string, ...HandlerFunc) IRoutes
	PATCH(string, ...HandlerFunc) IRoutes
	PUT(string, ...HandlerFunc) IRoutes
	OPTIONS(string, ...HandlerFunc) IRoutes
	HEAD(string, ...HandlerFunc) IRoutes
}

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 ResponseWriter

type ResponseWriter interface {

	// Returns the HTTP response status code of the current request.
	Status() int

	// Returns the number of bytes already written into the response http body.
	// See Written()
	Size() int
	Data() []byte
	// Writes the string into the response body.
	WriteString(string) (int, error)
	WriteHeader(code int)
	Write([]byte) (int, error)
	// Returns true if the response body was already written.
	Written() bool

	// Forces to write the http header (status code + headers).
	WriteHeaderNow()
	Header() http.Header
}

type RouteInfo

type RouteInfo struct {
	Method  string
	Path    string
	Handler string
}

type RouterGroup

type RouterGroup struct {
	Handlers HandlersChain
	// 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

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 github.

For GET, POST, PUT, PATCH 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) Use

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

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

type RoutesInfo

type RoutesInfo []RouteInfo

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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