server

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2021 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

*------------------------------------------------------------**

  • @filename jiny/context.go
  • @author jinycoo
  • @version 1.0.0
  • @date 2019-07-25 09:56
  • @desc jiny - context **------------------------------------------------------------*

*------------------------------------------------------------**

  • @filename jiny/params.go
  • @author jinycoo
  • @version 1.0.0
  • @date 2019-08-01 13:58
  • @desc jiny - params **------------------------------------------------------------*

*------------------------------------------------------------**

  • @filename jiny/jiny.go
  • @author jinycoo
  • @version 1.0.0
  • @date 2019-07-23 10:47
  • @desc jiny - entry framework **------------------------------------------------------------*

Index

Constants

View Source
const BindKey = "_jinycoo-BindK-888"

BindKey indicates a default bind key.

View Source
const (
	Version = "v1.0.0"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {
	context.Context

	Request *http.Request
	Writer  ResponseWriter

	Params Params

	// Keys is a key/value pair exclusively for the context of each request.
	Keys map[string]interface{}

	Error error
	// 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) 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

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP implements a best effort algorithm to return the real client IP, it parses X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy. Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.

func (*Context) ContentType

func (c *Context) ContentType() string

func (*Context) Cookie

func (c *Context) Cookie(name string) (string, error)

func (*Context) Copy

func (c *Context) Copy() *Context

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

func (*Context) DefaultQuery

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

func (c *Context) Done() <-chan struct{}

Done always returns nil (chan which will wait forever), if you want to abort your work when the connection was closed you should use Request.Context().Done() instead.

func (*Context) Err

func (c *Context) Err() error

Err always returns nil, maybe you want to use Request.Context().Err() instead.

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

func (*Context) FullPath

func (c *Context) FullPath() string

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

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

GetHeader returns value from request headers.

func (*Context) GetInt

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

func (*Context) GetInt64

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

func (*Context) GetParamInt

func (c *Context) GetParamInt(key string, def int) int

func (*Context) GetParamInt64

func (c *Context) GetParamInt64(key string, def int64) int64

func (*Context) GetParamString

func (c *Context) GetParamString(key string, def string) string

func (*Context) GetParamUint64

func (c *Context) GetParamUint64(key string, def uint64) uint64

func (*Context) GetQuery

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

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

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

func (*Context) GetRawData

func (c *Context) GetRawData() ([]byte, error)

GetRawData return stream data.

func (*Context) GetString

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

func (*Context) GetStringMap

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

func (*Context) Handler

func (c *Context) Handler() HandlerFn

func (*Context) HandlerName

func (c *Context) HandlerName() string

func (*Context) HandlerNames

func (c *Context) HandlerNames() []string

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

func (c *Context) IsAborted() bool

func (*Context) IsWebsocket

func (c *Context) IsWebsocket() bool

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

func (c *Context) MultipartForm() (*multipart.Form, error)

func (*Context) Next

func (c *Context) Next()

func (*Context) Param

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

func (*Context) ProtoBuf

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

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

func (*Context) Query

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

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

func (c *Context) QueryMap(key string) map[string]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)

Render writes the response headers and calls render.Render to render data.

func (*Context) SaveUploadedFile

func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error

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

func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

func (*Context) ShouldBind

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

func (*Context) ShouldBindHeader

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

ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).

func (*Context) ShouldBindJSON

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

ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON).

func (*Context) ShouldBindQuery

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

ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query).

func (*Context) ShouldBindUri

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

ShouldBindUri binds the passed struct pointer using the specified binding engine.

func (*Context) ShouldBindWith

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

ShouldBindWith binds the passed struct pointer using the specified binding engine. See the binding package.

func (*Context) ShouldBindXML

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

ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML).

func (*Context) ShouldBindYAML

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

ShouldBindYAML is a shortcut for c.ShouldBindWith(obj, binding.YAML).

func (*Context) Status

func (c *Context) Status(code int)

Status sets the HTTP response code.

func (*Context) Stream

func (c *Context) Stream(step func(w io.Writer) bool) bool

func (*Context) String

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

String writes the given string into the response body.

func (*Context) Value

func (c *Context) Value(key interface{}) interface{}

Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result.

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 Engine

type Engine struct {
	RouterGroup

	// 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
	ForwardedByClientIP    bool

	// #726 #755 If enabled, it will thrust some headers starting with
	// 'X-AppEngine...' for better integration with that PaaS.
	AppEngine bool

	// 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

	// Value of 'maxMemory' param that is given to http.Request's ParseMultipartForm
	// method call.
	MaxMultipartMemory int64

	// RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes.
	// See the PR #1817 and issue #1644
	RemoveExtraSlash 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 New

func New() *Engine

func (*Engine) HandleContext

func (engine *Engine) HandleContext(c *Context)

HandleContext re-enter a context that has been rewritten. This can be done by setting c.Request.URL.Path to your new target. Disclaimer: You can loop yourself to death with this, use wisely.

func (*Engine) NoMethod

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

NoMethod sets the handlers called when... TODO.

func (*Engine) NoRoute

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

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

func (*Engine) Routes

func (engine *Engine) 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 (*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) RunFd

func (engine *Engine) RunFd(fd int) (err error)

RunFd attaches the router to a http.Server and starts listening and serving HTTP requests through the specified file descriptor. Note: this method will block the calling goroutine indefinitely unless an error happens.

func (*Engine) RunListener

func (engine *Engine) RunListener(listener net.Listener) (err error)

RunListener attaches the router to a http.Server and starts listening and serving HTTP requests through the specified net.Listener

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

func (engine *Engine) SecureJsonPrefix(prefix string) *Engine

SecureJsonPrefix sets the secureJsonPrefix used in Context.SecureJSON.

func (*Engine) ServeHTTP

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

ServeHTTP conforms to the http.Handler interface.

func (*Engine) Use

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

Use attaches 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.

type H

type H map[string]interface{}

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

type HandlerFn

type HandlerFn func(*Context)

func Bind

func Bind(val interface{}) HandlerFn

Bind is a helper function for given interface object and returns a Gin middleware.

func WrapF

func WrapF(f http.HandlerFunc) HandlerFn

WrapF is a helper function for wrapping http.HandlerFunc and returns a Gin middleware.

func WrapH

func WrapH(h http.Handler) HandlerFn

WrapH is a helper function for wrapping http.Handler and returns a Gin middleware.

type HandlersChain

type HandlersChain []HandlerFn

func (HandlersChain) Last

func (c HandlersChain) Last() HandlerFn

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

type IRouter

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

IRouter defines all router handle interface includes single and group router.

type IRoutes

type IRoutes interface {
	Use(...HandlerFn) IRoutes

	Handle(string, string, ...HandlerFn) IRoutes
	Any(string, ...HandlerFn) IRoutes
	GET(string, ...HandlerFn) IRoutes
	POST(string, ...HandlerFn) IRoutes
	DELETE(string, ...HandlerFn) IRoutes
	PATCH(string, ...HandlerFn) IRoutes
	PUT(string, ...HandlerFn) IRoutes
	OPTIONS(string, ...HandlerFn) IRoutes
	HEAD(string, ...HandlerFn) IRoutes
}

IRoutes defines all router handle interface.

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 {
	http.ResponseWriter
	http.Hijacker
	http.Flusher
	http.CloseNotifier

	// 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

	// Writes the string into the response body.
	WriteString(string) (int, error)

	// Returns true if the response body was already written.
	Written() bool

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

	// get the http.Pusher for server push
	Pusher() http.Pusher
}

ResponseWriter ...

type RouteInfo

type RouteInfo struct {
	Method    string
	Path      string
	Handler   string
	HandlerFn HandlerFn
}

RouteInfo represents a request route's specification which contains method and path and its handler.

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 ...HandlerFn) 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 returns the base path of router group. For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api".

func (*RouterGroup) DELETE

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

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

func (*RouterGroup) GET

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

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

func (*RouterGroup) Group

func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFn) *RouterGroup

Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix. For example, all the routes that use a common middleware for authorization could be grouped.

func (*RouterGroup) HEAD

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

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

func (*RouterGroup) Handle

func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFn) 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 ...HandlerFn) IRoutes

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

func (*RouterGroup) PATCH

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

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

func (*RouterGroup) POST

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

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

func (*RouterGroup) PUT

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

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

func (*RouterGroup) Use

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

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

type RoutesInfo

type RoutesInfo []RouteInfo

RoutesInfo defines a RouteInfo array.

Jump to

Keyboard shortcuts

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