app

package
v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2024 License: Apache-2.0 Imports: 35 Imported by: 1,403

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetHandlerName

func GetHandlerName(handler HandlerFunc) string

func ParseByteRange

func ParseByteRange(byteRange []byte, contentLength int) (startPos, endPos int, err error)

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 SetConcurrentHandlerNameOperator added in v0.8.0

func SetConcurrentHandlerNameOperator()

func SetHandlerName

func SetHandlerName(handler HandlerFunc, name string)

func SetHandlerNameOperator added in v0.8.0

func SetHandlerNameOperator(o HandlerNameOperator)

Types

type ClientIP

type ClientIP func(ctx *RequestContext) string

func ClientIPWithOption added in v0.6.0

func ClientIPWithOption(opts ClientIPOptions) ClientIP

ClientIPWithOption used to generate custom ClientIP function and set by engine.SetClientIPFunc

type ClientIPOptions added in v0.6.0

type ClientIPOptions struct {
	RemoteIPHeaders []string
	TrustedCIDRs    []*net.IPNet
}

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 added in v0.5.0

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 HandlerNameOperator added in v0.8.0

type HandlerNameOperator interface {
	SetHandlerName(handler HandlerFunc, name string)
	GetHandlerName(handler HandlerFunc) string
}

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

type HijackHandler func(c network.Conn)

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 added in v0.7.0

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 added in v0.7.0

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 added in v0.7.0

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 added in v0.7.0

func (ctx *RequestContext) BindJSON(obj interface{}) error

BindJSON binds JSON body from *RequestContext. NOTE: obj should be a pointer.

func (*RequestContext) BindPath added in v0.7.0

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 added in v0.7.0

func (ctx *RequestContext) BindProtobuf(obj interface{}) error

BindProtobuf binds protobuf body from *RequestContext. NOTE: obj should be a pointer.

func (*RequestContext) BindQuery added in v0.7.0

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 added in v0.1.0

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) Exile added in v0.9.0

func (ctx *RequestContext) Exile()

Exile marks this RequestContext as not to be recycled. Experimental features: Use with caution, it may have a slight impact on performance.

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 added in v0.6.0

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 added in v0.4.1

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 added in v0.4.1

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) GetPostFormArray added in v0.9.3

func (ctx *RequestContext) GetPostFormArray(key string) ([]string, bool)

GetPostFormArray is like PostFormArray(key). It returns the specified key from a POST urlencoded form or multipart form when it exists `([]string, true)` (even when the value is an empty string), otherwise it returns ([]string(nil), false).

For example, during a PATCH request to update the item's tags:

    tag=tag1 tag=tag2 tag=tag3  -->  (["tag1", "tag2", "tag3"], true) := GetPostFormArray("tags") // set tags to ["tag1", "tag2", "tag3"]
	   tags=                  -->  (nil, true) := GetPostFormArray("tags") // set tags to nil
                            -->  (nil, false) := GetPostFormArray("tags") // do nothing with tags

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 added in v0.4.1

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 added in v0.4.1

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 added in v0.4.1

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)

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

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,

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 added in v0.4.0

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) IsExiled added in v0.9.0

func (ctx *RequestContext) IsExiled() 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) PostFormArray added in v0.9.3

func (ctx *RequestContext) PostFormArray(key string) []string

PostFormArray returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns an empty array `([])`.

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)

Redirect returns an HTTP redirect to the specific location. Note that this will not stop the current handler. In other words, even if Redirect() is called, the remaining handlers will still be executed and cause unexpected result. So it should call Abort to ensure the remaining handlers of this request will not be called.

ctx.Abort()
return

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 added in v0.7.0

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 added in v0.5.0

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 added in v0.3.1

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 added in v0.5.0

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) SetIndex added in v0.8.0

func (ctx *RequestContext) SetIndex(index int8)

SetIndex reset the handler's execution index Disclaimer: You can loop yourself to deal with this, use wisely.

func (*RequestContext) SetPartitionedCookie added in v0.9.0

func (ctx *RequestContext) SetPartitionedCookie(name, value string, maxAge int, path, domain string, sameSite protocol.CookieSameSite, secure, httpOnly bool)

SetPartitionedCookie adds a partitioned cookie to the Response's headers. Use protocol.CookieSameSiteNoneMode for cross-site cookies to work.

Usage: ctx.SetPartitionedCookie("user", "name", 10, "/", "localhost", protocol.CookieSameSiteNoneMode, true, true)

This adds the response header: Set-Cookie: user=name; Max-Age=10; Domain=localhost; Path=/; HttpOnly; Secure; SameSite=None; Partitioned

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 added in v0.7.0

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 added in v0.6.5

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 added in v0.6.5

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 added in v0.6.5

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 added in v0.6.5

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

Jump to

Keyboard shortcuts

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