server

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: May 14, 2024 License: MIT Imports: 33 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Handle

func Handle[IN Request, OUT any](handlers ...func(*Context, IN) (OUT, error))

func Hertz

func Hertz(devMode bool, opts ...config.Option) *server.Hertz

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

func WithALPN(enable bool) config.Option

WithALPN sets whether enable ALPN.

func WithAltTransport

func WithAltTransport(transporter func(options *config.Options) network.Transporter) config.Option

WithAltTransport sets which network library to use as an alternative transporter(need to be implemented by specific transporter).

func WithAutoReloadRender

func WithAutoReloadRender(b bool, interval time.Duration) config.Option

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

func WithBasePath(basePath string) config.Option

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

func WithCustomBinder(b binding.Binder) config.Option

WithCustomBinder sets customized Binder.

func WithCustomValidator

func WithCustomValidator(b binding.StructValidator) config.Option

WithCustomValidator sets customized Binder.

func WithDisableDefaultContentType

func WithDisableDefaultContentType(disable bool) config.Option

func WithDisableDefaultDate

func WithDisableDefaultDate(disable bool) config.Option

func WithDisableHeaderNamesNormalizing

func WithDisableHeaderNamesNormalizing(disable bool) config.Option

WithDisableHeaderNamesNormalizing is used to set whether disable header names normalizing.

func WithDisablePreParseMultipartForm

func WithDisablePreParseMultipartForm(b bool) config.Option

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

func WithDisablePrintRoute(b bool) config.Option

WithDisablePrintRoute sets whether disable debugPrintRoute If we don't set it, it will default to false

func WithExitWaitTime

func WithExitWaitTime(timeout time.Duration) config.Option

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

func WithGetOnly(isOnly bool) config.Option

WithGetOnly sets whether accept GET request only. Default: false

func WithH2C

func WithH2C(enable bool) config.Option

WithH2C sets whether enable H2C.

func WithHandleMethodNotAllowed

func WithHandleMethodNotAllowed(b bool) config.Option

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

func WithHostPorts(hp string) config.Option

WithHostPorts sets listening address.

func WithIdleTimeout

func WithIdleTimeout(t time.Duration) config.Option

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

func WithKeepAlive(b bool) config.Option

WithKeepAlive sets Whether use long connection. Default: true

func WithKeepAliveTimeout

func WithKeepAliveTimeout(t time.Duration) config.Option

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

func WithMaxKeepBodySize(bs int) config.Option

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

func WithMaxRequestBodySize(bs int) config.Option

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

func WithNetwork(nw string) config.Option

WithNetwork sets network. Support "tcp", "udp", "unix"(unix domain socket).

func WithOnAccept

func WithOnAccept(fn func(conn net.Conn) context.Context) config.Option

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

func WithOnConnect(fn func(ctx context.Context, conn network.Conn) context.Context) config.Option

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

func WithReadBufferSize(size int) config.Option

WithReadBufferSize sets the read buffer size which also limit the header size.

func WithReadTimeout

func WithReadTimeout(t time.Duration) config.Option

WithReadTimeout sets read timeout.

Close the connection when read request timeout.

func WithRedirectFixedPath

func WithRedirectFixedPath(b bool) config.Option

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

func WithRedirectTrailingSlash(b bool) config.Option

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

func WithRegistry(r registry.Registry, info *registry.Info) config.Option

WithRegistry sets the registry and registry's info

func WithRemoveExtraSlash

func WithRemoveExtraSlash(b bool) config.Option

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

func WithStreamBody(b bool) config.Option

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

func WithTLS(cfg *tls.Config) config.Option

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

func WithTraceLevel(level stats.Level) config.Option

WithTraceLevel sets the level trace.

func WithTracer

func WithTracer(t tracer.Tracer) config.Option

WithTracer adds tracer to server.

func WithTransport

func WithTransport(transporter func(options *config.Options) network.Transporter) config.Option

WithTransport sets which network library to use.

func WithUnescapePathValues

func WithUnescapePathValues(b bool) config.Option

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

func WithUseRawPath(b bool) config.Option

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.

func WithWriteTimeout

func WithWriteTimeout(t time.Duration) config.Option

WithWriteTimeout sets write timeout.

Connection will be closed when write request timeout.

Types

type Context

type Context struct {
	context.Context //nolint
	// contains filtered or unexported fields
}

func (*Context) ClientIP

func (ctx *Context) 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 (*Context) ContentType

func (ctx *Context) ContentType() []byte

ContentType returns the Content-Type header of the request.

func (*Context) Cookie

func (ctx *Context) Cookie(key string) []byte

Cookie returns the value of the request cookie key.

func (*Context) ForEachKey

func (ctx *Context) ForEachKey(f func(key string, v any))

Loop fn for every k/v in Keys

func (*Context) FullPath

func (ctx *Context) 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 (*Context) Host

func (ctx *Context) Host() []byte

The host is valid until returning from RequestHandler.

func (*Context) Identity

func (ctx *Context) Identity() Identity

func (*Context) IfModifiedSince

func (ctx *Context) 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 (*Context) IsEnableTrace

func (ctx *Context) IsEnableTrace() bool

func (*Context) Path

func (ctx *Context) Path() []byte

Path returns requested path.

The path is valid until returning from RequestHandler.

func (*Context) RemoteAddr

func (ctx *Context) RemoteAddr() net.Addr

RemoteAddr returns client address for the given request.

If address is nil, it will return zeroTCPAddr.

func (*Context) RequestBodyStream

func (ctx *Context) RequestBodyStream() io.Reader

func (*Context) SaveUploadedFile

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

SaveUploadedFile uploads the form file to specific dst.

func (*Context) Set

func (ctx *Context) Set(key string, value any)

Set is used to store a new key/value pair exclusively for this context. It also lazy initializes c.Keys if it was not used previously.

func (*Context) SetCookie

func (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

func (ctx *Context) SetEnableTrace(enable bool)

SetEnableTrace sets whether enable trace.

NOTE: biz handler must not modify this value, otherwise, it may panic.

func (*Context) SetHeader

func (ctx *Context) SetHeader(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 (*Context) SetIdentity

func (ctx *Context) SetIdentity(identity Identity)

func (*Context) URI

func (ctx *Context) URI() *protocol.URI

URI returns requested uri.

The uri is valid until returning from RequestHandler.

func (*Context) UserAgent

func (ctx *Context) UserAgent() []byte

UserAgent returns the value of the request user_agent.

func (*Context) Value

func (ctx *Context) Value(key any) any

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.

type Empty added in v0.1.1

type Empty struct{}

func (*Empty) Validate added in v0.1.1

func (e *Empty) Validate(*Context) error

type Handler

type Handler[IN Request, OUT any] struct {
	Action    func(*Context, IN) (OUT, error)
	RespondFn func(ctx *app.RequestContext, response any)
	// contains filtered or unexported fields
}

type Identity

type Identity map[string]any

type Request added in v0.1.1

type Request interface {
	Validator
}

type Validator added in v0.1.1

type Validator interface {
	Validate(ctx *Context) error
}

Jump to

Keyboard shortcuts

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