Documentation ¶
Index ¶
- func AddDecorator(name string, f decoratorFn)
- func Hertz(devMode bool, opts ...config.Option) *server.Hertz
- func NoMethod(handlers ...app.HandlerFunc)
- func NoRoute(handlers ...app.HandlerFunc)
- func Register[IN any, OUT any](action func(context.Context, *Request, IN) (OUT, error))
- func SetIdentifier(identifierFn identifierFn)
- func Static(relativePath, root string)
- func StaticFile(relativePath, filepath string)
- func Use(handlers ...app.HandlerFunc)
- func WithALPN(enable bool) config.Option
- func WithAltTransport(transporter func(options *config.Options) network.Transporter) config.Option
- func WithAutoReloadRender(b bool, interval time.Duration) config.Option
- func WithBasePath(basePath string) config.Option
- func WithBindConfig(bc *binding.BindConfig) config.Option
- func WithCustomBinder(b binding.Binder) config.Option
- func WithCustomValidator(b binding.StructValidator) config.Option
- func WithDisableDefaultContentType(disable bool) config.Option
- func WithDisableDefaultDate(disable bool) config.Option
- func WithDisableHeaderNamesNormalizing(disable bool) config.Option
- func WithDisablePreParseMultipartForm(b bool) config.Option
- func WithDisablePrintRoute(b bool) config.Option
- func WithExitWaitTime(timeout time.Duration) config.Option
- func WithGetOnly(isOnly bool) config.Option
- func WithH2C(enable bool) config.Option
- func WithHandleMethodNotAllowed(b bool) config.Option
- func WithHostPorts(hp string) config.Option
- func WithIdleTimeout(t time.Duration) config.Option
- func WithKeepAlive(b bool) config.Option
- func WithKeepAliveTimeout(t time.Duration) config.Option
- func WithListenConfig(l *net.ListenConfig) config.Option
- func WithMaxKeepBodySize(bs int) config.Option
- func WithMaxRequestBodySize(bs int) config.Option
- func WithNetwork(nw string) config.Option
- func WithOnAccept(fn func(conn net.Conn) context.Context) config.Option
- func WithOnConnect(fn func(ctx context.Context, conn network.Conn) context.Context) config.Option
- func WithReadBufferSize(size int) config.Option
- func WithReadTimeout(t time.Duration) config.Option
- func WithRedirectFixedPath(b bool) config.Option
- func WithRedirectTrailingSlash(b bool) config.Option
- func WithRegistry(r registry.Registry, info *registry.Info) config.Option
- func WithRemoveExtraSlash(b bool) config.Option
- func WithStreamBody(b bool) config.Option
- func WithTLS(cfg *tls.Config) config.Option
- func WithTraceLevel(level stats.Level) config.Option
- func WithTracer(t tracer.Tracer) config.Option
- func WithTransport(transporter func(options *config.Options) network.Transporter) config.Option
- func WithUnescapePathValues(b bool) config.Option
- func WithUseRawPath(b bool) config.Option
- func WithValidateConfig(vc *binding.ValidateConfig) config.Option
- func WithWriteTimeout(t time.Duration) config.Option
- type Handler
- type Identity
- type Request
- func (req *Request) Abort()
- func (req *Request) AbortWithError(code int, err error) *errors.Error
- func (req *Request) AbortWithMsg(msg string, statusCode int)
- func (req *Request) AbortWithStatus(code int)
- func (req *Request) AbortWithStatusJSON(code int, jsonObj any)
- func (req *Request) ClientIP() string
- func (req *Request) ContentType() []byte
- func (req *Request) Cookie(key string) []byte
- func (req *Request) ForEachKey(f func(key string, v any))
- func (req *Request) FullPath() string
- func (req *Request) GetHeader(key string) []byte
- func (req *Request) Host() []byte
- func (req *Request) Identity() Identity
- func (req *Request) IfModifiedSince(lastModified time.Time) bool
- func (req *Request) IsEnableTrace() bool
- func (req *Request) Method() string
- func (req *Request) Next(c context.Context)
- func (req *Request) Path() []byte
- func (req *Request) RemoteAddr() net.Addr
- func (req *Request) RequestBodyStream() io.Reader
- func (req *Request) SaveUploadedFile(file *multipart.FileHeader, dst string) error
- func (req *Request) Set(key string, value any)
- func (req *Request) SetCookie(name, value string, maxAge int, path, domain string, ...)
- func (req *Request) SetEnableTrace(enable bool)
- func (req *Request) SetHeader(key, value string)
- func (req *Request) SetIdentity(identity Identity)
- func (req *Request) URI() *protocol.URI
- func (req *Request) UserAgent() []byte
- func (req *Request) Value(key any) any
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddDecorator ¶ added in v1.2.0
func AddDecorator(name string, f decoratorFn)
func NoMethod ¶
func NoMethod(handlers ...app.HandlerFunc)
NoMethod sets the handlers called when the HTTP method does not match.
func NoRoute ¶
func NoRoute(handlers ...app.HandlerFunc)
NoRoute adds handlers for NoRoute. It returns a 404 code by default.
func SetIdentifier ¶ added in v1.0.0
func SetIdentifier(identifierFn identifierFn)
SetIdentifier set authentication and authorization method
func Static ¶
func Static(relativePath, root string)
Static serves files from the given file system root. To use the operating system's file system implementation, use :
router.Static("/static", "/var/www")
func StaticFile ¶
func StaticFile(relativePath, filepath string)
StaticFile registers a single route in order to Serve a single file of the local filesystem. router.StaticFile("favicon.ico", "./resources/favicon.ico")
func Use ¶
func Use(handlers ...app.HandlerFunc)
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.
func WithAltTransport ¶
WithAltTransport sets which network library to use as an alternative transporter(need to be implemented by specific transporter).
func WithAutoReloadRender ¶
WithAutoReloadRender sets the config of auto reload render. If auto reload render is enabled: 1. interval = 0 means reload render according to file watch mechanism.(recommended) 2. interval > 0 means reload render every interval.
func WithBasePath ¶
WithBasePath sets basePath.Must be "/" prefix and suffix,If not the default concatenate "/"
func WithBindConfig ¶
func WithBindConfig(bc *binding.BindConfig) config.Option
WithBindConfig sets bind config.
func WithCustomBinder ¶
WithCustomBinder sets customized Binder.
func WithCustomValidator ¶
func WithCustomValidator(b binding.StructValidator) config.Option
WithCustomValidator sets customized Binder.
func WithDisableDefaultDate ¶
func WithDisableHeaderNamesNormalizing ¶
WithDisableHeaderNamesNormalizing is used to set whether disable header names normalizing.
func WithDisablePreParseMultipartForm ¶
WithDisablePreParseMultipartForm sets disablePreParseMultipartForm.
This option is useful for servers that desire to treat multipart form data as a binary blob, or choose when to parse the data. Server pre parses multipart form data by default.
func WithDisablePrintRoute ¶
WithDisablePrintRoute sets whether disable debugPrintRoute If we don't set it, it will default to false
func WithExitWaitTime ¶
WithExitWaitTime sets timeout for graceful shutdown.
The server may exit ahead after all connections closed. All responses after shutdown will be added 'Connection: close' header.
func WithGetOnly ¶
WithGetOnly sets whether accept GET request only. Default: false
func WithHandleMethodNotAllowed ¶
WithHandleMethodNotAllowed sets handleMethodNotAllowed.
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.
func WithHostPorts ¶
WithHostPorts sets listening address.
func WithIdleTimeout ¶
WithIdleTimeout sets idle timeout.
Close the connection when the successive request timeout (in keepalive mode). Set this to protect server from misbehavior clients.
func WithKeepAlive ¶
WithKeepAlive sets Whether use long connection. Default: true
func WithKeepAliveTimeout ¶
WithKeepAliveTimeout sets keep-alive timeout.
In most cases, there is no need to care about this option.
func WithListenConfig ¶
func WithListenConfig(l *net.ListenConfig) config.Option
WithListenConfig sets listener config.
func WithMaxKeepBodySize ¶
WithMaxKeepBodySize sets max size of request/response body to keep when recycled. Unit: byte
Body buffer which larger than this size will be put back into buffer poll.
func WithMaxRequestBodySize ¶
WithMaxRequestBodySize sets the limitation of request body size. Unit: byte
Body buffer which larger than this size will be put back into buffer poll.
func WithNetwork ¶
WithNetwork sets network. Support "tcp", "udp", "unix"(unix domain socket).
func WithOnAccept ¶
WithOnAccept sets the callback function when a new connection is accepted but cannot receive data in netpoll. In go net, it will be called before converting tls connection
func WithOnConnect ¶
WithOnConnect sets the onConnect function. It can received data from connection in netpoll. In go net, it will be called after converting tls connection.
func WithReadBufferSize ¶
WithReadBufferSize sets the read buffer size which also limit the header size.
func WithReadTimeout ¶
WithReadTimeout sets read timeout.
Close the connection when read request timeout.
func WithRedirectFixedPath ¶
WithRedirectFixedPath sets redirectFixedPath.
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 308 for all other request methods. For example /FOO and /..//Foo could be redirected to /foo. RedirectTrailingSlash is independent of this option.
func WithRedirectTrailingSlash ¶
WithRedirectTrailingSlash sets redirectTrailingSlash.
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.
func WithRegistry ¶
WithRegistry sets the registry and registry's info
func WithRemoveExtraSlash ¶
WithRemoveExtraSlash sets removeExtraSlash.
RemoveExtraSlash a parameter can be parsed from the URL even with extra slashes. If UseRawPath is false (by default), the RemoveExtraSlash effectively is true, as url.Path gonna be used, which is already cleaned.
func WithStreamBody ¶
WithStreamBody determines whether read body in stream or not.
StreamRequestBody enables streaming request body, and calls the handler sooner when given body is larger than the current limit.
func WithTLS ¶
WithTLS sets TLS config to start a tls server.
NOTE: If a tls server is started, it won't accept non-tls request.
func WithTraceLevel ¶
WithTraceLevel sets the level trace.
func WithTransport ¶
WithTransport sets which network library to use.
func WithUnescapePathValues ¶
WithUnescapePathValues sets unescapePathValues.
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.
func WithUseRawPath ¶
WithUseRawPath sets useRawPath.
If enabled, the url.RawPath will be used to find parameters.
func WithValidateConfig ¶
func WithValidateConfig(vc *binding.ValidateConfig) config.Option
WithValidateConfig sets validate config.
Types ¶
type Request ¶ added in v0.1.1
type Request struct {
// contains filtered or unexported fields
}
func (*Request) Abort ¶ added in v1.1.0
func (req *Request) Abort()
Don't use Abort method in handlers. It just use for middlewares
func (*Request) AbortWithError ¶ added in v1.1.0
Don't use AbortWithError method in handlers. It just use for middlewares
func (*Request) AbortWithMsg ¶ added in v1.1.0
Don't use AbortWithMsg method in handlers. It just use for middlewares
func (*Request) AbortWithStatus ¶ added in v1.1.0
Don't use AbortWithStatus method in handlers. It just use for middlewares
func (*Request) AbortWithStatusJSON ¶ added in v1.1.0
Don't use AbortWithStatusJSON method in handlers. It just use for middlewares
func (*Request) ClientIP ¶ added in v1.1.0
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 (*Request) ContentType ¶ added in v1.1.0
ContentType returns the Content-Type header of the request.
func (*Request) ForEachKey ¶ added in v1.1.0
Loop fn for every k/v in Keys
func (*Request) FullPath ¶ added in v1.1.0
FullPath returns a matched route full path. For not found routes returns an empty string.
router.GET("/user/:id", func(c context.Context, req *app.RequestContext) { req.FullPath() == "/user/:id" // true })
func (*Request) IfModifiedSince ¶ added in v1.1.0
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 (*Request) IsEnableTrace ¶ added in v1.1.0
func (*Request) Next ¶ added in v1.1.0
Next should be used only inside middleware. It executes the pending handlers in the chain inside the calling handler.
func (*Request) Path ¶ added in v1.1.0
Path returns requested path.
The path is valid until returning from RequestHandler.
func (*Request) RemoteAddr ¶ added in v1.1.0
RemoteAddr returns client address for the given request.
If address is nil, it will return zeroTCPAddr.
func (*Request) RequestBodyStream ¶ added in v1.1.0
func (*Request) SaveUploadedFile ¶ added in v1.1.0
func (req *Request) SaveUploadedFile(file *multipart.FileHeader, dst string) error
SaveUploadedFile uploads the form file to specific dst.
func (*Request) Set ¶ added in v1.1.0
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 (*Request) SetCookie ¶ added in v1.1.0
func (req *Request) 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. req.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. req.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. req.SetCookie("", "hertz", 10, "/", "localhost",protocol.CookieSameSiteLaxMode, false, false) add response header ---> Set-Cookie: hertz; max-age=10; domain=localhost; path=/; SameSite=Lax; 4. req.SetCookie("user", "", 10, "/", "localhost",protocol.CookieSameSiteLaxMode, false, false) add response header ---> Set-Cookie: user=; max-age=10; domain=localhost; path=/; SameSite=Lax;
func (*Request) SetEnableTrace ¶ added in v1.1.0
SetEnableTrace sets whether enable trace.
NOTE: biz handler must not modify this value, otherwise, it may panic.
func (*Request) SetHeader ¶ added in v1.1.0
Header is an intelligent shortcut for req.Response.Header.Set(key, value). It writes a header in the response. If value == "", this method removes the header `req.Response.Header.Del(key)`.
func (*Request) SetIdentity ¶ added in v1.1.0
func (*Request) URI ¶ added in v1.1.0
URI returns requested uri.
The uri is valid until returning from RequestHandler.