Documentation ¶
Index ¶
- func GetHandlerName(handler HandlerFunc) string
- func ParseByteRange(byteRange []byte, contentLength int) (startPos, endPos int, err error)
- func ServeFile(ctx *RequestContext, path string)
- func ServeFileUncompressed(ctx *RequestContext, path string)
- func SetClientIPFunc(fn ClientIP)
- func SetHandlerName(handler HandlerFunc, name string)
- type ClientIP
- type ClientIPOptions
- type FS
- type FormValueFunc
- type Handler
- type HandlerFunc
- type HandlersChain
- type HijackHandler
- type PathRewriteFunc
- type RequestContext
- func (ctx *RequestContext) Abort()
- func (ctx *RequestContext) AbortWithError(code int, err error) *errors.Error
- func (ctx *RequestContext) AbortWithMsg(msg string, statusCode int)
- func (ctx *RequestContext) AbortWithStatus(code int)
- func (ctx *RequestContext) AbortWithStatusJSON(code int, jsonObj interface{})
- func (ctx *RequestContext) Bind(obj interface{}) error
- func (ctx *RequestContext) BindAndValidate(obj interface{}) error
- func (ctx *RequestContext) BindByContentType(obj interface{}) error
- func (ctx *RequestContext) BindForm(obj interface{}) error
- func (ctx *RequestContext) BindHeader(obj interface{}) error
- func (ctx *RequestContext) BindJSON(obj interface{}) error
- func (ctx *RequestContext) BindPath(obj interface{}) error
- func (ctx *RequestContext) BindProtobuf(obj interface{}) error
- func (ctx *RequestContext) BindQuery(obj interface{}) error
- func (ctx *RequestContext) Body() ([]byte, error)
- func (ctx *RequestContext) ClientIP() string
- func (ctx *RequestContext) ContentType() []byte
- func (ctx *RequestContext) Cookie(key string) []byte
- func (ctx *RequestContext) Copy() *RequestContext
- func (ctx *RequestContext) Data(code int, contentType string, data []byte)
- func (ctx *RequestContext) DefaultPostForm(key, defaultValue string) string
- func (ctx *RequestContext) DefaultQuery(key, defaultValue string) string
- func (ctx *RequestContext) Error(err error) *errors.Error
- func (ctx *RequestContext) File(filepath string)
- func (ctx *RequestContext) FileAttachment(filepath, filename string)
- func (ctx *RequestContext) FileFromFS(filepath string, fs *FS)
- func (ctx *RequestContext) Finished() <-chan struct{}
- func (ctx *RequestContext) Flush() error
- func (ctx *RequestContext) ForEachKey(fn func(k string, v interface{}))
- func (ctx *RequestContext) FormFile(name string) (*multipart.FileHeader, error)
- func (ctx *RequestContext) FormValue(key string) []byte
- func (ctx *RequestContext) FullPath() string
- func (ctx *RequestContext) Get(key string) (value interface{}, exists bool)
- func (ctx *RequestContext) GetBool(key string) (b bool)
- func (ctx *RequestContext) GetConn() network.Conn
- func (ctx *RequestContext) GetDuration(key string) (d time.Duration)
- func (ctx *RequestContext) GetFloat32(key string) (f32 float32)
- func (ctx *RequestContext) GetFloat64(key string) (f64 float64)
- func (ctx *RequestContext) GetHeader(key string) []byte
- func (ctx *RequestContext) GetHijackHandler() HijackHandler
- func (ctx *RequestContext) GetIndex() int8
- func (ctx *RequestContext) GetInt(key string) (i int)
- func (ctx *RequestContext) GetInt32(key string) (i32 int32)
- func (ctx *RequestContext) GetInt64(key string) (i64 int64)
- func (ctx *RequestContext) GetPostForm(key string) (string, bool)
- func (ctx *RequestContext) GetQuery(key string) (string, bool)
- func (ctx *RequestContext) GetRawData() []byte
- func (ctx *RequestContext) GetReader() network.Reader
- func (ctx *RequestContext) GetRequest() (dst *protocol.Request)
- func (ctx *RequestContext) GetResponse() (dst *protocol.Response)
- func (ctx *RequestContext) GetString(key string) (s string)
- func (ctx *RequestContext) GetStringMap(key string) (sm map[string]interface{})
- func (ctx *RequestContext) GetStringMapString(key string) (sms map[string]string)
- func (ctx *RequestContext) GetStringMapStringSlice(key string) (smss map[string][]string)
- func (ctx *RequestContext) GetStringSlice(key string) (ss []string)
- func (ctx *RequestContext) GetTime(key string) (t time.Time)
- func (ctx *RequestContext) GetTraceInfo() traceinfo.TraceInfo
- func (ctx *RequestContext) GetUint(key string) (ui uint)
- func (ctx *RequestContext) GetUint32(key string) (ui32 uint32)
- func (ctx *RequestContext) GetUint64(key string) (ui64 uint64)
- func (ctx *RequestContext) GetWriter() network.Writer
- func (ctx *RequestContext) HTML(code int, name string, obj interface{})
- func (ctx *RequestContext) Handler() HandlerFunc
- func (ctx *RequestContext) HandlerName() string
- func (ctx *RequestContext) Handlers() HandlersChain
- func (ctx *RequestContext) Header(key, value string)
- func (ctx *RequestContext) Hijack(handler HijackHandler)
- func (ctx *RequestContext) Hijacked() bool
- func (ctx *RequestContext) Host() []byte
- func (ctx *RequestContext) IfModifiedSince(lastModified time.Time) bool
- func (ctx *RequestContext) IndentedJSON(code int, obj interface{})
- func (ctx *RequestContext) IsAborted() bool
- func (ctx *RequestContext) IsEnableTrace() bool
- func (ctx *RequestContext) IsGet() bool
- func (ctx *RequestContext) IsHead() bool
- func (ctx *RequestContext) IsPost() bool
- func (ctx *RequestContext) JSON(code int, obj interface{})
- func (ctx *RequestContext) Method() []byte
- func (ctx *RequestContext) MultipartForm() (*multipart.Form, error)
- func (ctx *RequestContext) MustGet(key string) interface{}
- func (ctx *RequestContext) Next(c context.Context)
- func (ctx *RequestContext) NotFound()
- func (ctx *RequestContext) NotModified()
- func (ctx *RequestContext) Param(key string) string
- func (ctx *RequestContext) Path() []byte
- func (ctx *RequestContext) PostArgs() *protocol.Args
- func (ctx *RequestContext) PostForm(key string) string
- func (ctx *RequestContext) ProtoBuf(code int, obj interface{})
- func (ctx *RequestContext) PureJSON(code int, obj interface{})
- func (ctx *RequestContext) Query(key string) string
- func (ctx *RequestContext) QueryArgs() *protocol.Args
- func (ctx *RequestContext) Redirect(statusCode int, uri []byte)
- func (ctx *RequestContext) RemoteAddr() net.Addr
- func (ctx *RequestContext) Render(code int, r render.Render)
- func (ctx *RequestContext) RequestBodyStream() io.Reader
- func (ctx *RequestContext) Reset()
- func (ctx *RequestContext) ResetWithoutConn()
- func (ctx *RequestContext) SaveUploadedFile(file *multipart.FileHeader, dst string) error
- func (ctx *RequestContext) Set(key string, value interface{})
- func (ctx *RequestContext) SetBinder(binder binding.Binder)
- func (ctx *RequestContext) SetBodyStream(bodyStream io.Reader, bodySize int)
- func (ctx *RequestContext) SetBodyString(body string)
- func (ctx *RequestContext) SetClientIPFunc(f ClientIP)
- func (ctx *RequestContext) SetConn(c network.Conn)
- func (ctx *RequestContext) SetConnectionClose()
- func (ctx *RequestContext) SetContentType(contentType string)
- func (ctx *RequestContext) SetContentTypeBytes(contentType []byte)
- func (ctx *RequestContext) SetCookie(name, value string, maxAge int, path, domain string, ...)
- func (ctx *RequestContext) SetEnableTrace(enable bool)
- func (ctx *RequestContext) SetFormValueFunc(f FormValueFunc)
- func (ctx *RequestContext) SetFullPath(p string)
- func (ctx *RequestContext) SetHandlers(hc HandlersChain)
- func (ctx *RequestContext) SetHijackHandler(h HijackHandler)
- func (ctx *RequestContext) SetStatusCode(statusCode int)
- func (ctx *RequestContext) SetTraceInfo(t traceinfo.TraceInfo)
- func (ctx *RequestContext) SetValidator(validator binding.StructValidator)
- func (ctx *RequestContext) Status(code int)
- func (ctx *RequestContext) String(code int, format string, values ...interface{})
- func (ctx *RequestContext) URI() *protocol.URI
- func (ctx *RequestContext) UserAgent() []byte
- func (ctx *RequestContext) Validate(obj interface{}) error
- func (ctx *RequestContext) Value(key interface{}) interface{}
- func (ctx *RequestContext) VisitAllCookie(f func(key, value []byte))
- func (ctx *RequestContext) VisitAllHeaders(f func(key, value []byte))
- func (ctx *RequestContext) VisitAllPostArgs(f func(key, value []byte))
- func (ctx *RequestContext) VisitAllQueryArgs(f func(key, value []byte))
- func (ctx *RequestContext) Write(p []byte) (int, error)
- func (ctx *RequestContext) WriteString(s string) (int, error)
- func (ctx *RequestContext) XML(code int, obj interface{})
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetHandlerName ¶
func GetHandlerName(handler HandlerFunc) string
func ParseByteRange ¶
ParseByteRange parses 'Range: bytes=...' header value.
It follows https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 .
func ServeFile ¶
func ServeFile(ctx *RequestContext, path string)
ServeFile returns HTTP response containing compressed file contents from the given path.
HTTP response may contain uncompressed file contents in the following cases:
- Missing 'Accept-Encoding: gzip' request header.
- No write access to directory containing the file.
Directory contents is returned if path points to directory.
Use ServeFileUncompressed is you don't need serving compressed file contents.
func ServeFileUncompressed ¶
func ServeFileUncompressed(ctx *RequestContext, path string)
ServeFileUncompressed returns HTTP response containing file contents from the given path.
Directory contents is returned if path points to directory.
ServeFile may be used for saving network traffic when serving files with good compression ratio.
func SetClientIPFunc ¶
func SetClientIPFunc(fn ClientIP)
SetClientIPFunc sets ClientIP function implementation to get ClientIP. Deprecated: Use engine.SetClientIPFunc instead of SetClientIPFunc
func SetHandlerName ¶
func SetHandlerName(handler HandlerFunc, name string)
Types ¶
type ClientIP ¶
type ClientIP func(ctx *RequestContext) string
func ClientIPWithOption ¶
func ClientIPWithOption(opts ClientIPOptions) ClientIP
ClientIPWithOption used to generate custom ClientIP function and set by engine.SetClientIPFunc
type ClientIPOptions ¶
type FS ¶
type FS struct { // Path to the root directory to serve files from. Root string // List of index file names to try opening during directory access. // // For example: // // * index.html // * index.htm // * my-super-index.xml // // By default the list is empty. IndexNames []string // Index pages for directories without files matching IndexNames // are automatically generated if set. // // Directory index generation may be quite slow for directories // with many files (more than 1K), so it is discouraged enabling // index pages' generation for such directories. // // By default index pages aren't generated. GenerateIndexPages bool // Transparently compresses responses if set to true. // // The server tries minimizing CPU usage by caching compressed files. // It adds CompressedFileSuffix suffix to the original file name and // tries saving the resulting compressed file under the new file name. // So it is advisable to give the server write access to Root // and to all inner folders in order to minimize CPU usage when serving // compressed responses. // // Transparent compression is disabled by default. Compress bool // Enables byte range requests if set to true. // // Byte range requests are disabled by default. AcceptByteRange bool // Path rewriting function. // // By default request path is not modified. PathRewrite PathRewriteFunc // PathNotFound fires when file is not found in filesystem // this functions tries to replace "Cannot open requested path" // server response giving to the programmer the control of server flow. // // By default PathNotFound returns // "Cannot open requested path" PathNotFound HandlerFunc // Expiration duration for inactive file handlers. // // FSHandlerCacheDuration is used by default. CacheDuration time.Duration // Suffix to add to the name of cached compressed file. // // This value has sense only if Compress is set. // // FSCompressedFileSuffix is used by default. CompressedFileSuffix string // contains filtered or unexported fields }
FS represents settings for request handler serving static files from the local filesystem.
It is prohibited copying FS values. Create new values instead.
func (*FS) NewRequestHandler ¶
func (fs *FS) NewRequestHandler() HandlerFunc
NewRequestHandler returns new request handler with the given FS settings.
The returned handler caches requested file handles for FS.CacheDuration. Make sure your program has enough 'max open files' limit aka 'ulimit -n' if FS.Root folder contains many files.
Do not create multiple request handlers from a single FS instance - just reuse a single request handler.
type FormValueFunc ¶
type FormValueFunc func(*RequestContext, string) []byte
type Handler ¶
type Handler interface {
ServeHTTP(c context.Context, ctx *RequestContext)
}
type HandlerFunc ¶
type HandlerFunc func(c context.Context, ctx *RequestContext)
type HandlersChain ¶
type HandlersChain []HandlerFunc
HandlersChain defines a HandlerFunc array.
func (HandlersChain) Last ¶
func (c HandlersChain) Last() HandlerFunc
Last returns the last handler of the handler chain.
Generally speaking, the last handler is the main handler.
type HijackHandler ¶
HijackHandler must process the hijacked connection c.
If KeepHijackedConns is disabled, which is by default, the connection c is automatically closed after returning from HijackHandler.
The connection c must not be used after returning from the handler, if KeepHijackedConns is disabled.
When KeepHijackedConns enabled, hertz will not Close() the connection, you must do it when you need it. You must not use c in any way after calling Close().
network.Connection provide two options of io: net.Conn and zero-copy read/write
type PathRewriteFunc ¶
type PathRewriteFunc func(ctx *RequestContext) []byte
PathRewriteFunc must return new request path based on arbitrary ctx info such as ctx.Path().
Path rewriter is used in FS for translating the current request to the local filesystem path relative to FS.Root.
The returned path must not contain '/../' substrings due to security reasons, since such paths may refer files outside FS.Root.
The returned path may refer to ctx members. For example, ctx.Path().
func NewPathSlashesStripper ¶
func NewPathSlashesStripper(slashesCount int) PathRewriteFunc
NewPathSlashesStripper returns path rewriter, which strips slashesCount leading slashes from the path.
Examples:
- slashesCount = 0, original path: "/foo/bar", result: "/foo/bar"
- slashesCount = 1, original path: "/foo/bar", result: "/bar"
- slashesCount = 2, original path: "/foo/bar", result: ""
The returned path rewriter may be used as FS.PathRewrite .
func NewVHostPathRewriter ¶
func NewVHostPathRewriter(slashesCount int) PathRewriteFunc
NewVHostPathRewriter returns path rewriter, which strips slashesCount leading slashes from the path and prepends the path with request's host, thus simplifying virtual hosting for static files.
Examples:
host=foobar.com, slashesCount=0, original path="/foo/bar". Resulting path: "/foobar.com/foo/bar"
host=img.aaa.com, slashesCount=1, original path="/images/123/456.jpg" Resulting path: "/img.aaa.com/123/456.jpg"
type RequestContext ¶
type RequestContext struct { Request protocol.Request Response protocol.Response // Errors is a list of errors attached to all the handlers/middlewares who used this context. Errors errors.ErrorChain Params param.Params HTMLRender render.HTMLRender // Keys is a key/value pair exclusively for the context of each request. Keys map[string]interface{} // contains filtered or unexported fields }
func NewContext ¶
func NewContext(maxParams uint16) *RequestContext
NewContext make a pure RequestContext without any http request/response information
Set the Request filed before use it for handlers
func (*RequestContext) Abort ¶
func (ctx *RequestContext) 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 (*RequestContext) AbortWithError ¶
func (ctx *RequestContext) AbortWithError(code int, err error) *errors.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 RequestContext.Error() for more details.
func (*RequestContext) AbortWithMsg ¶
func (ctx *RequestContext) AbortWithMsg(msg string, statusCode int)
AbortWithMsg sets response status code to the given value and sets response body to the given message.
Warning: this will reset the response headers and body already set!
func (*RequestContext) AbortWithStatus ¶
func (ctx *RequestContext) 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 (*RequestContext) AbortWithStatusJSON ¶
func (ctx *RequestContext) 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 (*RequestContext) Bind ¶
func (ctx *RequestContext) Bind(obj interface{}) error
Bind binds data from *RequestContext to obj. NOTE: obj should be a pointer.
func (*RequestContext) BindAndValidate ¶
func (ctx *RequestContext) BindAndValidate(obj interface{}) error
BindAndValidate binds data from *RequestContext to obj and validates them if needed. NOTE: obj should be a pointer.
func (*RequestContext) BindByContentType ¶
func (ctx *RequestContext) BindByContentType(obj interface{}) error
BindByContentType will select the binding type on the ContentType automatically. NOTE: obj should be a pointer.
func (*RequestContext) BindForm ¶
func (ctx *RequestContext) BindForm(obj interface{}) error
BindForm binds form parameters from *RequestContext to obj with 'form' tag. It will only use 'form' tag for binding. NOTE: obj should be a pointer.
func (*RequestContext) BindHeader ¶
func (ctx *RequestContext) BindHeader(obj interface{}) error
BindHeader binds header parameters from *RequestContext to obj with 'header' tag. It will only use 'header' tag for binding. NOTE: obj should be a pointer.
func (*RequestContext) BindJSON ¶
func (ctx *RequestContext) BindJSON(obj interface{}) error
BindJSON binds JSON body from *RequestContext. NOTE: obj should be a pointer.
func (*RequestContext) BindPath ¶
func (ctx *RequestContext) BindPath(obj interface{}) error
BindPath binds router parameters from *RequestContext to obj with 'path' tag. It will only use 'path' tag for binding. NOTE: obj should be a pointer.
func (*RequestContext) BindProtobuf ¶
func (ctx *RequestContext) BindProtobuf(obj interface{}) error
BindProtobuf binds protobuf body from *RequestContext. NOTE: obj should be a pointer.
func (*RequestContext) BindQuery ¶
func (ctx *RequestContext) BindQuery(obj interface{}) error
BindQuery binds query parameters from *RequestContext to obj with 'query' tag. It will only use 'query' tag for binding. NOTE: obj should be a pointer.
func (*RequestContext) Body ¶
func (ctx *RequestContext) Body() ([]byte, error)
Body returns body data
func (*RequestContext) ClientIP ¶
func (ctx *RequestContext) ClientIP() string
ClientIP tries to parse the headers in [X-Real-Ip, X-Forwarded-For]. It calls RemoteIP() under the hood. If it cannot satisfy the requirements, use engine.SetClientIPFunc to inject your own implementation.
func (*RequestContext) ContentType ¶
func (ctx *RequestContext) ContentType() []byte
ContentType returns the Content-Type header of the request.
func (*RequestContext) Cookie ¶
func (ctx *RequestContext) Cookie(key string) []byte
Cookie returns the value of the request cookie key.
func (*RequestContext) Copy ¶
func (ctx *RequestContext) Copy() *RequestContext
Copy returns a copy of the current context that can be safely used outside the request's scope.
NOTE: If you want to pass requestContext to a goroutine, call this method to get a copy of requestContext.
func (*RequestContext) Data ¶
func (ctx *RequestContext) Data(code int, contentType string, data []byte)
Data writes some data into the body stream and updates the HTTP code.
func (*RequestContext) DefaultPostForm ¶
func (ctx *RequestContext) DefaultPostForm(key, defaultValue string) string
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 (*RequestContext) DefaultQuery ¶
func (ctx *RequestContext) DefaultQuery(key, defaultValue string) string
DefaultQuery returns the keyed url query value if it exists, otherwise it returns the specified defaultValue string.
func (*RequestContext) Error ¶
func (ctx *RequestContext) Error(err error) *errors.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 (*RequestContext) File ¶
func (ctx *RequestContext) File(filepath string)
File writes the specified file into the body stream in an efficient way.
func (*RequestContext) FileAttachment ¶
func (ctx *RequestContext) FileAttachment(filepath, filename string)
FileAttachment use an efficient way to write the file to body stream.
When client download the file, it will rename the file as filename
func (*RequestContext) FileFromFS ¶
func (ctx *RequestContext) FileFromFS(filepath string, fs *FS)
func (*RequestContext) Finished ¶
func (ctx *RequestContext) Finished() <-chan struct{}
func (*RequestContext) Flush ¶
func (ctx *RequestContext) Flush() error
Flush is the shortcut for ctx.Response.GetHijackWriter().Flush(). Will return nil if the response writer is not hijacked.
func (*RequestContext) ForEachKey ¶
func (ctx *RequestContext) ForEachKey(fn func(k string, v interface{}))
Loop fn for every k/v in Keys
func (*RequestContext) FormFile ¶
func (ctx *RequestContext) FormFile(name string) (*multipart.FileHeader, error)
FormFile returns the first file for the provided form key.
func (*RequestContext) FormValue ¶
func (ctx *RequestContext) FormValue(key string) []byte
FormValue returns form value associated with the given key.
The value is searched in the following places:
- Query string.
- POST or PUT body.
There are more fine-grained methods for obtaining form values:
- QueryArgs for obtaining values from query string.
- PostArgs for obtaining values from POST or PUT body.
- MultipartForm for obtaining values from multipart form.
- FormFile for obtaining uploaded files.
The returned value is valid until returning from RequestHandler. Use engine.SetCustomFormValueFunc to change action of FormValue.
func (*RequestContext) FullPath ¶
func (ctx *RequestContext) FullPath() string
FullPath returns a matched route full path. For not found routes returns an empty string.
router.GET("/user/:id", func(c context.Context, ctx *app.RequestContext) { ctx.FullPath() == "/user/:id" // true })
func (*RequestContext) Get ¶
func (ctx *RequestContext) Get(key string) (value interface{}, exists bool)
Get returns the value for the given key, ie: (value, true). If the value does not exist it returns (nil, false)
func (*RequestContext) GetBool ¶
func (ctx *RequestContext) GetBool(key string) (b bool)
GetBool returns the value associated with the key as a boolean. Return false when type is error.
func (*RequestContext) GetConn ¶
func (ctx *RequestContext) GetConn() network.Conn
func (*RequestContext) GetDuration ¶
func (ctx *RequestContext) GetDuration(key string) (d time.Duration)
GetDuration returns the value associated with the key as a duration. Return time.Duration(0) when type is error.
func (*RequestContext) GetFloat32 ¶
func (ctx *RequestContext) GetFloat32(key string) (f32 float32)
GetFloat32 returns the value associated with the key as a float32. Return float32(0.0) when type is error.
func (*RequestContext) GetFloat64 ¶
func (ctx *RequestContext) GetFloat64(key string) (f64 float64)
GetFloat64 returns the value associated with the key as a float64. Return 0.0 when type is error.
func (*RequestContext) GetHeader ¶
func (ctx *RequestContext) GetHeader(key string) []byte
GetHeader returns value from request headers.
func (*RequestContext) GetHijackHandler ¶
func (ctx *RequestContext) GetHijackHandler() HijackHandler
func (*RequestContext) GetIndex ¶
func (ctx *RequestContext) GetIndex() int8
func (*RequestContext) GetInt ¶
func (ctx *RequestContext) GetInt(key string) (i int)
GetInt returns the value associated with the key as an integer. Return 0 when type is error.
func (*RequestContext) GetInt32 ¶
func (ctx *RequestContext) GetInt32(key string) (i32 int32)
GetInt32 returns the value associated with the key as an integer. Return int32(0) when type is error.
func (*RequestContext) GetInt64 ¶
func (ctx *RequestContext) GetInt64(key string) (i64 int64)
GetInt64 returns the value associated with the key as an integer. Return int64(0) when type is error.
func (*RequestContext) GetPostForm ¶
func (ctx *RequestContext) GetPostForm(key string) (string, 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 (*RequestContext) GetQuery ¶
func (ctx *RequestContext) GetQuery(key string) (string, bool)
GetQuery returns the keyed url query value
if it exists `(value, true)` (even when the value is an empty string) will be returned, otherwise it returns `("", false)`. For example:
GET /?name=Manu&lastname= ("Manu", true) == c.GetQuery("name") ("", false) == c.GetQuery("id") ("", true) == c.GetQuery("lastname")
func (*RequestContext) GetRawData ¶
func (ctx *RequestContext) GetRawData() []byte
GetRawData returns body data.
func (*RequestContext) GetReader ¶
func (ctx *RequestContext) GetReader() network.Reader
func (*RequestContext) GetRequest ¶
func (ctx *RequestContext) GetRequest() (dst *protocol.Request)
GetRequest returns a copy of Request.
func (*RequestContext) GetResponse ¶
func (ctx *RequestContext) GetResponse() (dst *protocol.Response)
GetResponse returns a copy of Response.
func (*RequestContext) GetString ¶
func (ctx *RequestContext) GetString(key string) (s string)
GetString returns the value associated with the key as a string. Return "" when type is error.
func (*RequestContext) GetStringMap ¶
func (ctx *RequestContext) GetStringMap(key string) (sm map[string]interface{})
GetStringMap returns the value associated with the key as a map of interfaces.
Return map[string]interface{}(nil) when type is error.
func (*RequestContext) GetStringMapString ¶
func (ctx *RequestContext) GetStringMapString(key string) (sms map[string]string)
GetStringMapString returns the value associated with the key as a map of strings.
Return map[string]string(nil) when type is error.
func (*RequestContext) GetStringMapStringSlice ¶
func (ctx *RequestContext) GetStringMapStringSlice(key string) (smss map[string][]string)
GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
Return map[string][]string(nil) when type is error.
func (*RequestContext) GetStringSlice ¶
func (ctx *RequestContext) GetStringSlice(key string) (ss []string)
GetStringSlice returns the value associated with the key as a slice of strings.
Return []string(nil) when type is error.
func (*RequestContext) GetTime ¶
func (ctx *RequestContext) GetTime(key string) (t time.Time)
GetTime returns the value associated with the key as time. Return time.Time{} when type is error.
func (*RequestContext) GetTraceInfo ¶
func (ctx *RequestContext) GetTraceInfo() traceinfo.TraceInfo
func (*RequestContext) GetUint ¶
func (ctx *RequestContext) GetUint(key string) (ui uint)
GetUint returns the value associated with the key as an unsigned integer. Return uint(0) when type is error.
func (*RequestContext) GetUint32 ¶
func (ctx *RequestContext) GetUint32(key string) (ui32 uint32)
GetUint32 returns the value associated with the key as an unsigned integer. Return uint32(0) when type is error.
func (*RequestContext) GetUint64 ¶
func (ctx *RequestContext) GetUint64(key string) (ui64 uint64)
GetUint64 returns the value associated with the key as an unsigned integer. Return uint64(0) when type is error.
func (*RequestContext) GetWriter ¶
func (ctx *RequestContext) GetWriter() network.Writer
func (*RequestContext) HTML ¶
func (ctx *RequestContext) HTML(code int, name string, obj interface{})
HTML renders the HTTP template specified by its file name.
It also updates the HTTP code and sets the Content-Type as "text/html". See http://golang.org/doc/articles/wiki/
func (*RequestContext) Handler ¶
func (ctx *RequestContext) Handler() HandlerFunc
Handler returns the main handler.
func (*RequestContext) HandlerName ¶
func (ctx *RequestContext) HandlerName() string
HandlerName returns the main handler's name.
For example if the handler is "handleGetUsers()", this function will return "main.handleGetUsers".
func (*RequestContext) Handlers ¶
func (ctx *RequestContext) Handlers() HandlersChain
Handlers returns the handler chain.
func (*RequestContext) Header ¶
func (ctx *RequestContext) Header(key, value string)
func (*RequestContext) Hijack ¶
func (ctx *RequestContext) Hijack(handler HijackHandler)
Hijack registers the given handler for connection hijacking.
The handler is called after returning from RequestHandler and sending http response. The current connection is passed to the handler. The connection is automatically closed after returning from the handler.
The server skips calling the handler in the following cases:
- 'Connection: close' header exists in either request or response.
- Unexpected error during response writing to the connection.
The server stops processing requests from hijacked connections.
Server limits such as Concurrency, ReadTimeout, WriteTimeout, etc. aren't applied to hijacked connections.
The handler must not retain references to ctx members.
Arbitrary 'Connection: Upgrade' protocols may be implemented with HijackHandler. For instance,
- WebSocket ( https://en.wikipedia.org/wiki/WebSocket )
- HTTP/2.0 ( https://en.wikipedia.org/wiki/HTTP/2 )
func (*RequestContext) Hijacked ¶
func (ctx *RequestContext) Hijacked() bool
Hijacked returns true after Hijack is called.
func (*RequestContext) Host ¶
func (ctx *RequestContext) Host() []byte
Host returns requested host.
The host is valid until returning from RequestHandler.
func (*RequestContext) IfModifiedSince ¶
func (ctx *RequestContext) IfModifiedSince(lastModified time.Time) bool
IfModifiedSince returns true if lastModified exceeds 'If-Modified-Since' value from the request header.
The function returns true also 'If-Modified-Since' request header is missing.
func (*RequestContext) IndentedJSON ¶
func (ctx *RequestContext) 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".
func (*RequestContext) IsAborted ¶
func (ctx *RequestContext) IsAborted() bool
IsAborted returns true if the current context has aborted.
func (*RequestContext) IsEnableTrace ¶
func (ctx *RequestContext) IsEnableTrace() bool
func (*RequestContext) IsGet ¶
func (ctx *RequestContext) IsGet() bool
IsGet returns true if request method is GET.
func (*RequestContext) IsHead ¶
func (ctx *RequestContext) IsHead() bool
IsHead returns true if request method is HEAD.
func (*RequestContext) IsPost ¶
func (ctx *RequestContext) IsPost() bool
IsPost returns true if request method is POST.
func (*RequestContext) JSON ¶
func (ctx *RequestContext) 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 (*RequestContext) Method ¶
func (ctx *RequestContext) Method() []byte
Method return request method.
Returned value is valid until returning from RequestHandler.
func (*RequestContext) MultipartForm ¶
func (ctx *RequestContext) MultipartForm() (*multipart.Form, error)
MultipartForm returns request's multipart form.
Returns errNoMultipartForm if request's content-type isn't 'multipart/form-data'.
All uploaded temporary files are automatically deleted after returning from RequestHandler. Either move or copy uploaded files into new place if you want retaining them.
Use SaveMultipartFile function for permanently saving uploaded file.
The returned form is valid until returning from RequestHandler.
See also FormFile and FormValue.
func (*RequestContext) MustGet ¶
func (ctx *RequestContext) MustGet(key string) interface{}
MustGet returns the value for the given key if it exists, otherwise it panics.
func (*RequestContext) Next ¶
func (ctx *RequestContext) Next(c context.Context)
Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler.
func (*RequestContext) NotFound ¶
func (ctx *RequestContext) NotFound()
NotFound resets response and sets '404 Not Found' response status code.
func (*RequestContext) NotModified ¶
func (ctx *RequestContext) NotModified()
NotModified resets response and sets '304 Not Modified' response status code.
func (*RequestContext) Param ¶
func (ctx *RequestContext) 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 context.Context, ctx *app.RequestContext) { // a GET request to /user/john id := ctx.Param("id") // id == "john" })
func (*RequestContext) Path ¶
func (ctx *RequestContext) Path() []byte
Path returns requested path.
The path is valid until returning from RequestHandler.
func (*RequestContext) PostArgs ¶
func (ctx *RequestContext) PostArgs() *protocol.Args
PostArgs returns POST arguments.
It doesn't return query arguments from RequestURI - use QueryArgs for this. Returned arguments are valid until returning from RequestHandler. See also QueryArgs, FormValue and FormFile.
func (*RequestContext) PostForm ¶
func (ctx *RequestContext) PostForm(key string) string
PostForm returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns an empty string `("")`.
func (*RequestContext) ProtoBuf ¶
func (ctx *RequestContext) ProtoBuf(code int, obj interface{})
ProtoBuf serializes the given struct as ProtoBuf into the response body.
func (*RequestContext) PureJSON ¶
func (ctx *RequestContext) PureJSON(code int, obj interface{})
PureJSON serializes the given struct as JSON into the response body. PureJSON, unlike JSON, does not replace special html characters with their unicode entities.
func (*RequestContext) Query ¶
func (ctx *RequestContext) Query(key string) string
Query returns the keyed url query value if it exists, otherwise it returns an empty string `("")`.
For example:
GET /path?id=1234&name=Manu&value= c.Query("id") == "1234" c.Query("name") == "Manu" c.Query("value") == "" c.Query("wtf") == ""
func (*RequestContext) QueryArgs ¶
func (ctx *RequestContext) QueryArgs() *protocol.Args
QueryArgs returns query arguments from RequestURI.
It doesn't return POST'ed arguments - use PostArgs() for this. Returned arguments are valid until returning from RequestHandler. See also PostArgs, FormValue and FormFile.
func (*RequestContext) Redirect ¶
func (ctx *RequestContext) Redirect(statusCode int, uri []byte)
func (*RequestContext) RemoteAddr ¶
func (ctx *RequestContext) RemoteAddr() net.Addr
RemoteAddr returns client address for the given request.
If address is nil, it will return zeroTCPAddr.
func (*RequestContext) Render ¶
func (ctx *RequestContext) Render(code int, r render.Render)
Render writes the response headers and calls render.Render to render data.
func (*RequestContext) RequestBodyStream ¶
func (ctx *RequestContext) RequestBodyStream() io.Reader
func (*RequestContext) Reset ¶
func (ctx *RequestContext) Reset()
Reset resets requestContext.
NOTE: It is an internal function. You should not use it.
func (*RequestContext) ResetWithoutConn ¶
func (ctx *RequestContext) ResetWithoutConn()
func (*RequestContext) SaveUploadedFile ¶
func (ctx *RequestContext) SaveUploadedFile(file *multipart.FileHeader, dst string) error
SaveUploadedFile uploads the form file to specific dst.
func (*RequestContext) Set ¶
func (ctx *RequestContext) 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 (*RequestContext) SetBinder ¶
func (ctx *RequestContext) SetBinder(binder binding.Binder)
func (*RequestContext) SetBodyStream ¶
func (ctx *RequestContext) SetBodyStream(bodyStream io.Reader, bodySize int)
SetBodyStream sets response body stream and, optionally body size.
bodyStream.Close() is called after finishing reading all body data if it implements io.Closer.
If bodySize is >= 0, then bodySize bytes must be provided by bodyStream before returning io.EOF.
If bodySize < 0, then bodyStream is read until io.EOF.
See also SetBodyStreamWriter.
func (*RequestContext) SetBodyString ¶
func (ctx *RequestContext) SetBodyString(body string)
SetBodyString sets response body to the given value.
func (*RequestContext) SetClientIPFunc ¶
func (ctx *RequestContext) SetClientIPFunc(f ClientIP)
func (*RequestContext) SetConn ¶
func (ctx *RequestContext) SetConn(c network.Conn)
func (*RequestContext) SetConnectionClose ¶
func (ctx *RequestContext) SetConnectionClose()
SetConnectionClose sets 'Connection: close' response header.
func (*RequestContext) SetContentType ¶
func (ctx *RequestContext) SetContentType(contentType string)
SetContentType sets response Content-Type.
func (*RequestContext) SetContentTypeBytes ¶
func (ctx *RequestContext) SetContentTypeBytes(contentType []byte)
SetContentTypeBytes sets response Content-Type.
It is safe modifying contentType buffer after function return.
func (*RequestContext) SetCookie ¶
func (ctx *RequestContext) SetCookie(name, value string, maxAge int, path, domain string, sameSite protocol.CookieSameSite, secure, httpOnly bool)
SetCookie adds a Set-Cookie header to the Response's headers.
Parameter introduce: name and value is used to set cookie's name and value, eg. Set-Cookie: name=value maxAge is use to set cookie's expiry date, eg. Set-Cookie: name=value; max-age=1 path and domain is used to set the scope of a cookie, eg. Set-Cookie: name=value;domain=localhost; path=/; secure and httpOnly is used to sent cookies securely; eg. Set-Cookie: name=value;HttpOnly; secure; sameSite let servers specify whether/when cookies are sent with cross-site requests; eg. Set-Cookie: name=value;HttpOnly; secure; SameSite=Lax; For example: 1. ctx.SetCookie("user", "hertz", 1, "/", "localhost",protocol.CookieSameSiteLaxMode, true, true) add response header ---> Set-Cookie: user=hertz; max-age=1; domain=localhost; path=/; HttpOnly; secure; SameSite=Lax; 2. ctx.SetCookie("user", "hertz", 10, "/", "localhost",protocol.CookieSameSiteLaxMode, false, false) add response header ---> Set-Cookie: user=hertz; max-age=10; domain=localhost; path=/; SameSite=Lax; 3. ctx.SetCookie("", "hertz", 10, "/", "localhost",protocol.CookieSameSiteLaxMode, false, false) add response header ---> Set-Cookie: hertz; max-age=10; domain=localhost; path=/; SameSite=Lax; 4. ctx.SetCookie("user", "", 10, "/", "localhost",protocol.CookieSameSiteLaxMode, false, false) add response header ---> Set-Cookie: user=; max-age=10; domain=localhost; path=/; SameSite=Lax;
func (*RequestContext) SetEnableTrace ¶
func (ctx *RequestContext) SetEnableTrace(enable bool)
SetEnableTrace sets whether enable trace.
NOTE: biz handler must not modify this value, otherwise, it may panic.
func (*RequestContext) SetFormValueFunc ¶
func (ctx *RequestContext) SetFormValueFunc(f FormValueFunc)
func (*RequestContext) SetFullPath ¶
func (ctx *RequestContext) SetFullPath(p string)
func (*RequestContext) SetHandlers ¶
func (ctx *RequestContext) SetHandlers(hc HandlersChain)
func (*RequestContext) SetHijackHandler ¶
func (ctx *RequestContext) SetHijackHandler(h HijackHandler)
func (*RequestContext) SetStatusCode ¶
func (ctx *RequestContext) SetStatusCode(statusCode int)
SetStatusCode sets response status code.
func (*RequestContext) SetTraceInfo ¶
func (ctx *RequestContext) SetTraceInfo(t traceinfo.TraceInfo)
func (*RequestContext) SetValidator ¶
func (ctx *RequestContext) SetValidator(validator binding.StructValidator)
func (*RequestContext) Status ¶
func (ctx *RequestContext) Status(code int)
Status sets the HTTP response code.
func (*RequestContext) String ¶
func (ctx *RequestContext) String(code int, format string, values ...interface{})
func (*RequestContext) URI ¶
func (ctx *RequestContext) URI() *protocol.URI
URI returns requested uri.
The uri is valid until returning from RequestHandler.
func (*RequestContext) UserAgent ¶
func (ctx *RequestContext) UserAgent() []byte
UserAgent returns the value of the request user_agent.
func (*RequestContext) Validate ¶
func (ctx *RequestContext) Validate(obj interface{}) error
Validate validates obj with "vd" tag NOTE: obj should be a pointer.
func (*RequestContext) Value ¶
func (ctx *RequestContext) 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.
In case the Key is reset after response, Value() return nil if ctx.Key is nil.
func (*RequestContext) VisitAllCookie ¶
func (ctx *RequestContext) VisitAllCookie(f func(key, value []byte))
VisitAllCookie calls f for each request cookie.
f must not retain references to key and/or value after returning.
func (*RequestContext) VisitAllHeaders ¶
func (ctx *RequestContext) VisitAllHeaders(f func(key, value []byte))
VisitAllHeaders calls f for each request header.
f must not retain references to key and/or value after returning. Copy key and/or value contents before returning if you need retaining them.
To get the headers in order they were received use VisitAllInOrder.
func (*RequestContext) VisitAllPostArgs ¶
func (ctx *RequestContext) VisitAllPostArgs(f func(key, value []byte))
VisitAllPostArgs calls f for each existing post arg.
f must not retain references to key and value after returning. Make key and/or value copies if you need storing them after returning.
func (*RequestContext) VisitAllQueryArgs ¶
func (ctx *RequestContext) VisitAllQueryArgs(f func(key, value []byte))
VisitAllQueryArgs calls f for each existing query arg.
f must not retain references to key and value after returning. Make key and/or value copies if you need storing them after returning.
func (*RequestContext) Write ¶
func (ctx *RequestContext) Write(p []byte) (int, error)
Write writes p into response body.
func (*RequestContext) WriteString ¶
func (ctx *RequestContext) WriteString(s string) (int, error)
WriteString appends s to response body.
func (*RequestContext) XML ¶
func (ctx *RequestContext) 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".