Documentation ¶
Index ¶
- func Handle[IN any, OUT any](handlers ...func(*Context, IN) (OUT, error))
- func Hertz(devMode bool, opts ...config.Option) *server.Hertz
- func NoMethod(handlers ...app.HandlerFunc)
- func NoRoute(handlers ...app.HandlerFunc)
- 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 Context
- func (ctx *Context) ClientIP() string
- func (ctx *Context) ContentType() []byte
- func (ctx *Context) Cookie(key string) []byte
- func (ctx *Context) ForEachKey(f func(key string, v any))
- func (ctx *Context) FullPath() string
- func (ctx *Context) Host() []byte
- func (ctx *Context) Identity() Identity
- func (ctx *Context) IfModifiedSince(lastModified time.Time) bool
- func (ctx *Context) IsEnableTrace() bool
- func (ctx *Context) Path() []byte
- func (ctx *Context) RemoteAddr() net.Addr
- func (ctx *Context) RequestBodyStream() io.Reader
- func (ctx *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
- func (ctx *Context) Set(key string, value any)
- func (ctx *Context) SetCookie(name, value string, maxAge int, path, domain string, ...)
- func (ctx *Context) SetEnableTrace(enable bool)
- func (ctx *Context) SetHeader(key, value string)
- func (ctx *Context) SetIdentity(identity Identity)
- func (ctx *Context) URI() *protocol.URI
- func (ctx *Context) UserAgent() []byte
- func (ctx *Context) Value(key any) any
- type Handler
- type Identity
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NoMethod ¶ added in v0.0.6
func NoMethod(handlers ...app.HandlerFunc)
NoMethod sets the handlers called when the HTTP method does not match.
func NoRoute ¶ added in v0.0.6
func NoRoute(handlers ...app.HandlerFunc)
NoRoute adds handlers for NoRoute. It returns a 404 code by default.
func Static ¶ added in v0.0.6
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 ¶ added in v0.0.6
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 ¶ added in v0.0.6
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 ¶ added in v0.0.6
WithAltTransport sets which network library to use as an alternative transporter(need to be implemented by specific transporter).
func WithAutoReloadRender ¶ added in v0.0.6
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 ¶ added in v0.0.6
func WithBindConfig(bc *binding.BindConfig) config.Option
WithBindConfig sets bind config.
func WithCustomBinder ¶ added in v0.0.6
WithCustomBinder sets customized Binder.
func WithCustomValidator ¶ added in v0.0.6
func WithCustomValidator(b binding.StructValidator) config.Option
WithCustomValidator sets customized Binder.
func WithDisableDefaultContentType ¶ added in v0.0.6
func WithDisableDefaultDate ¶ added in v0.0.6
func WithDisableHeaderNamesNormalizing ¶ added in v0.0.6
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 ¶ added in v0.0.6
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 ¶ added in v0.0.6
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 ¶ added in v0.0.6
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 ¶ added in v0.0.6
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 ¶ added in v0.0.6
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 ¶ added in v0.0.6
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 ¶ added in v0.0.6
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 ¶ added in v0.0.6
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 ¶ added in v0.0.6
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 ¶ added in v0.0.6
WithTraceLevel sets the level trace.
func WithTracer ¶ added in v0.0.6
WithTracer adds tracer to server.
func WithTransport ¶ added in v0.0.6
WithTransport sets which network library to use.
func WithUnescapePathValues ¶ added in v0.0.6
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 ¶ added in v0.0.6
func WithValidateConfig(vc *binding.ValidateConfig) config.Option
WithValidateConfig sets validate config.
Types ¶
type Context ¶
func (*Context) ClientIP ¶ added in v0.0.6
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 (*Context) ContentType ¶ added in v0.0.6
ContentType returns the Content-Type header of the request.
func (*Context) ForEachKey ¶ added in v0.0.6
Loop fn for every k/v in Keys
func (*Context) FullPath ¶
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 (*Context) IfModifiedSince ¶ added in v0.0.6
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 (*Context) IsEnableTrace ¶ added in v0.0.6
func (*Context) Path ¶
Path returns requested path.
The path is valid until returning from RequestHandler.
func (*Context) RemoteAddr ¶
RemoteAddr returns client address for the given request.
If address is nil, it will return zeroTCPAddr.
func (*Context) RequestBodyStream ¶ added in v0.0.6
func (*Context) SaveUploadedFile ¶ added in v0.0.6
func (ctx *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error
SaveUploadedFile uploads the form file to specific dst.
func (*Context) Set ¶
Set is used to store a new key/value pair exclusively for this context. It also lazy initializes c.Keys if it was not used previously.
func (*Context) SetCookie ¶ added in v0.0.6
func (ctx *Context) 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 (*Context) SetEnableTrace ¶ added in v0.0.6
SetEnableTrace sets whether enable trace.
NOTE: biz handler must not modify this value, otherwise, it may panic.
func (*Context) SetHeader ¶ added in v0.0.6
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 (*Context) SetIdentity ¶
func (*Context) URI ¶ added in v0.0.6
URI returns requested uri.
The uri is valid until returning from RequestHandler.