Configuration instruction

Hertz configuration instruction.

Server

The configuration items on the Server side all use server.xxx when initializing the Server, such as:

package main

import "github.com/cloudwego/hertz/pkg/app/server"

func main() {
	h := server.New(server.WithXXXX())
	...
}
Configuration NameTypeDescription
WithTransportnetwork.NewTransporterReplace the transport. Default:netpoll.NewTransporter
WithHostPortsstringSpecify the listening address and port
WithKeepAliveTimeouttime.DurationSet the keep-alive time of tcp persistent connection, generally no need to modify it, you should more pay attention to idleTimeout rather than modifying it. Default: 1min.
WithReadTimeouttime.DurationThe timeout of data reading. Default:3min.
WithIdleTimeouttime.DurationThe free timeout of the request link for persistent connection. Default: 3min.
WithMaxRequestBodySizeintMax body size of a request. Default: 4M (the corresponding value of 4M is 4*1024*1024).
WithRedirectTrailingSlashboolWhether to redirect with the / which is at the end of the router automatically. For example: If there is only /foo/ in the router, /foo will be redirected to /foo/. And if there is only /foo in the router, /foo/ will be redirected to /foo. Default: true.
WithRemoveExtraSlashboolRemoveExtraSlash makes the parameter still valid when it contains an extra /. For example, if WithRemoveExtraSlash is true user//xiaoming can match the user/:name router. Default: false.
WithUnescapePathValuesboolIf true, the request path will be escaped automatically (eg. ‘%2F’ -> ‘/’). If UseRawPath is false (the default), UnescapePathValues is true, because URI().Path() will be used and it is already escaped. To set WithUnescapePathValues to false, you need to set WithUseRawPath to true. Default (true).
WithUseRawPathboolIf true, the original path will be used to match the route. Default: false.
WithHandleMethodNotAllowedboolIf true when the current path cannot match any method, the server will check whether other methods are registered with the route of the current path, and if exist other methods, it will respond “Method Not Allowed” and return the status code 405; if not, it will use the handler of NotFound to handle it. Default: false.
WithDisablePreParseMultipartFormboolIf true, the multipart form will not be preprocessed. The body can be obtained via ctx.Request.Body() and then can be processed by user. Default: false.
WithStreamBodyboolIf true, the body will be handled by stream processing. Default: false.
WithNetworkstringSet the network protocol, optional: tcp,udp,unix(unix domain socket). Default: tcp.
ContinueHandlerfunc(header *RequestHeader) boolCall the ContinueHandler after receiving the Expect 100 Continue header. With ContinueHandler, the server can decide whether to read the potentially large request body based on the header.
PanicHandlerHandlerFuncHandle panic used to generate error pages and return error code 500.
NotFoundHandlerFuncThe handler to be called when the route does not match.
WithExitWaitTimetime.DurationSet the graceful exit time. the Server will stop connection establishment for new requests and set the Connection: Close header for each request after closing. When the set time is reached, Server will to be closed. the Server can be closed early when all connections have been closed. Default: 5s.
WithTLStls.ConfigConfiguring server tls capabilities.
WithListenConfignet.ListenConfigSet the listener configuration. Can be used to set whether to allow reuse ports, etc.
WithALPNboolWhether to enable ALPN. Default: false.
WithTracertracer.TracerInject tracer implementation, if not inject Tracer. Default: close.
WithTraceLevelstats.LevelSet trace level, Default: LevelDetailed.
WithWriteTimeouttime.DurationThe timeout of data writing. Default:infinite.
WithRedirectFixedPathboolIf enabled, if the current request path does not match, the server will try to repair the request path and re-match, if the match is successful and the request is a GET request, it will return status code 301 for redirect, other requests will return 308 for redirect. Disabled by default
WithBasePathstringSet the base path, which must be prefixed and suffixed with /. The default is /
WithMaxKeepBodySizeintSets the maximum size of the request body and response body to be retained during reclaim. Unit: Byte. Default value: 4 _ 1024 _ 1024
WithGetOnlyboolIf enabled, only GET requests are accepted. Disabled by default
WithKeepAliveboolIf enabled, use HTTP keepalive. Enabled by default
WithAltTransportnetwork.NewTransporterSet up the alternate transport. Default value: netpoll.NewTransporter
WithH2CboolSets whether H2C is enabled. Disabled by default
WithReadBufferSizeintSet the read buffer size while limiting the HTTP header size. Default value: 4 * 1024
WithRegistryregistry.Registry, *registry.InfoSetup registry configuration, service registration information. Default value: registry.NoopRegistry, nil
WithAutoReloadRenderbool, time.DurationSet up the automatic reload rendering configuration. Default value: false, 0
WithDisablePrintRouteboolSets whether debugPrintRoute is disabled. Default disable
WithOnAcceptfunc(conn net.Conn) context.ContextSet 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. Default value: nil
WithOnConnectfunc(ctx context.Context, conn network.Conn) context.ContextSet the onConnect function. It can received data from connection in netpoll. In go net, it will be called after converting tls connection. Default value: nil
WithDisableHeaderNamesNormalizingboolSets whether or not to disable Request and Response Header name normalization (capitalization of the first letter and the first letter after a dash)

Server Connection limitation:

  • If you are using the standard network library, there is no such restriction.
  • If netpoll is used, the maximum number of connections is 10000 (this is the gopool) used at the bottom of netpoll. Yes, the modification method is also very simple, just call the function provided by gopool: gopool.SetCap(xxx) (you can call it once in main.go).

Client

The configuration items on the Client side all use client.xxx when initializing the Client, such as:

package main

import "github.com/cloudwego/hertz/pkg/app/client"

func main() {
	c, err := client.NewClient(client.WithXxx())
	...
}
Configuration NameTypeDescription
WithDialTimeouttime.DurationConnection establishment timeout. Default: 1s.
WithMaxConnsPerHostintSet the maximum number of connections for every host. Default: 512.
WithMaxIdleConnDurationtime.DurationSet the idle connection timeout, which will close the connection after the timeout Default: 10s.
WithMaxConnDurationtime.DurationSet the maximum keep-alive time of the connection, when the timeout expired, the connection will be closed after the current request is completed. Default: infinite.
WithMaxConnWaitTimeouttime.DurationSet the maximum time to wait for an idle connection. Default: no wait.
WithKeepAliveboolWhether to use persistent connection. Default: true.
WithRetryConfig…retry.OptionSet the retry config of client. Hertz version >= v0.4.0.
WithMaxIdempotentCallAttemptsintSet the maximum number of calls. If a call fails, it will be retried. Default: 1 (That is no retry). v0.4.0 is obsolete. Only available before v0.4.0. It is recommended to upgrade Hertz version >= v0.4.0 and use WithRetryConfig instead.
WithClientReadTimeouttime.DurationSet the maximum time to read the response. Default: infinite.
WithTLSConfig*tls.ConfigSet the client’s TLS config for mutual TLS authentication.
WithDialernetwork.DialerSet the network library used by the client. Default: netpoll.
WithResponseBodyStreamboolSet whether to use stream processing. Default: false.
WithDialFuncclient.DialFuncSet Dial Function.
WithWriteTimeouttime.DurationThe timeout of data writing. Default:infinite.
WithHostClientConfigHookfunc(hc interface{}) errorSet the function hook for re-configure the host client. The function needs to assert the parameter hc as the required struct, such as http1.HostClient, and then perform specific processing.

Last modified July 24, 2024 : docs: fix error in render (#1110) (34e4f87)