Documentation
¶
Index ¶
- Variables
- func CalculateTimeouts(totalLifecycleTimeout time.Duration) (readHeaderTimeout, readTimeout, writeTimeout, idleTimeout time.Duration)
- func Control(network, address string, c syscall.RawConn) (err error)
- func GetIPAddress(ipAddresses []string, privateRanges []IPRange) (string, bool)
- func GetSubdomain(hostOrIP string) string
- func IPInRange(r IPRange, ipAddress net.IP) bool
- func IPIsPrivateSubnet(ipAddress net.IP, privateRanges []IPRange) bool
- func IPRangeEqual(a, b []IPRange) bool
- func IsLoopback(hostOrIP string) bool
- func IsRootDomain(hostOrIP string) bool
- func JoinURL(scheme, host string, port int) string
- func RegisterNgrokListener(fn NgrokListenerFunc)
- func ResolveHostname(addr string, hosts ...string) string
- func ShutdownSignal(ctx context.Context) <-chan struct{}
- func SplitURL(inputURL string) (scheme, host string, port int, err error)
- type IPRange
- type LimitsOptions
- type NgrokListenerFunc
- type NgrokOptions
- type NgrokTunnelListener
- type SSHTunnelOptions
- type Server
- func (s *Server) Close() error
- func (s *Server) ListenAndServe(handler http.Handler) error
- func (s *Server) OnListenerCreated(fn func(ln net.Listener, url *url.URL) error) *Server
- func (s *Server) Shutdown(ctx context.Context) error
- func (s *Server) String() string
- func (s *Server) Wait(ctx context.Context) error
- type ServerOptions
- type TimeoutOptions
- func (c *TimeoutOptions) ApplyToServer(srv *http.Server)
- func (c *TimeoutOptions) Get() *TimeoutOptions
- func (c *TimeoutOptions) TimeoutHandler(mainHandler http.Handler) http.Handler
- func (c *TimeoutOptions) WithHandlerTimeout(timeout time.Duration, htmlBody ...string) *TimeoutOptions
- func (c *TimeoutOptions) WithIdleTimeout(timeout time.Duration) *TimeoutOptions
- func (c *TimeoutOptions) WithReadHeaderTimeout(timeout time.Duration) *TimeoutOptions
- func (c *TimeoutOptions) WithReadTimeout(timeout time.Duration) *TimeoutOptions
- func (c *TimeoutOptions) WithServerTimeout(timeout time.Duration) *TimeoutOptions
- func (c *TimeoutOptions) WithShutdownOnInterruptTimeout(timeout time.Duration) *TimeoutOptions
- func (c *TimeoutOptions) WithWriteTimeout(timeout time.Duration) *TimeoutOptions
Constants ¶
This section is empty.
Variables ¶
var DefaultStartupLogger = os.Stdout
DefaultStartupLogger is the default logger which is used by the `printIPs` function.
var DefaultTimeoutMessage = `` /* 235-byte string literal not displayed */
DefaultTimeoutMessage is the default timeout message which is rendered on expired handlers when timeout handler is registered (see Timeout configuration field).
var GetRootDomain = func(hostOrIP string) string { if host, _, err := net.SplitHostPort(hostOrIP); err == nil { hostOrIP = host } if isLoopbackMap(hostOrIP) { return hostOrIP } if _, err := netip.ParseAddr(hostOrIP); err == nil { return hostOrIP } if rootDomain, err := publicsuffix.EffectiveTLDPlusOne(hostOrIP); err == nil { return rootDomain } return "" }
GetRootDomain returns the root domain of the given host.
Functions ¶
func CalculateTimeouts ¶
func CalculateTimeouts(totalLifecycleTimeout time.Duration) (readHeaderTimeout, readTimeout, writeTimeout, idleTimeout time.Duration)
CalculateTimeouts calculates the read and write timeouts based on the total lifecycle timeout.
Define the total timeout for the response-request lifecycle. This is the maximum amount of time the entire process should take. Divide the total timeout into portions for the read, write, and processing time. A common approach is to allocate 50% of the time to reading, 25% to processing, and 25% to writing. Set a minimum threshold for both read and write timeouts to ensure they are not too short, which could cause premature timeout errors. Define the idle timeout as a percentage of the total lifecycle timeout or as a fixed value, depending on your requirements. Ensure that the idle timeout is not greater than the read and write timeouts, as it should be a period of inactivity within reasonable bounds.
The total lifecycle timeout is divided into: 50% for read timeout 25% for processing time (not directly used but subtracted from the total to calculate write timeout) 25% for write timeout (calculated as the remainder after allocating read timeout and processing time) The read header timeout is set to 50% of the read timeout. The idle timeout is set to 75% of the read timeout. Minimum thresholds are applied to ensure that none of the timeouts fall below a certain value.
func GetIPAddress ¶
GetIPAddress returns a valid public IP Address from a collection of IP Addresses and a range of private subnets.
Reports whether a valid IP was found.
func GetSubdomain ¶
GetSubdomain returns the subdomain of the given host.
func IPIsPrivateSubnet ¶
IPIsPrivateSubnet reports whether this "ipAddress" is in a private subnet.
func IPRangeEqual ¶
IPRangeEqual reports whether two IPRange slices are equal.
func IsLoopback ¶
IsLoopback reports whether the host is a loopback address. It supports both IP addresses and hostnames. It returns true if the host is a loopback address, false otherwise. Note that the function might block while performing DNS queries.
func IsRootDomain ¶
IsRootDomain reports whether the host or ip is a root domain.
func RegisterNgrokListener ¶
func RegisterNgrokListener(fn NgrokListenerFunc)
RegisterNgrokListener sets the function the server calls to open a ngrok tunnel when ServerOptions.Ngrok is set. The package github.com/kataras/iris/v14/core/server/ngrok calls it from its init function, applications import that package instead of calling this. A later call replaces the earlier one. A nil fn removes the registration.
func ResolveHostname ¶
ResolveHostname resolves the hostname from the provided address. Rules:
- If the address is empty, it returns "localhost".
- If the address is a port, 2.1 If the port is 80 or 443 it returns "localhost" 2.2 Otherwise it returns "localhost" + port.
- If the address is a domain, it returns the domain.
- If the address is a port and a domain, it returns the domain.
func ShutdownSignal ¶
ShutdownSignal returns the channel that is closed when the server carrying ctx begins a graceful shutdown, or nil when ctx did not come from a server this package started.
It answers a question net/http does not. A request context is cancelled when the client disconnects, when an HTTP/2 stream is reset, or when ServeHTTP returns, and shutdown is on none of those lists - so a handler blocked in a stream loop is never told that the process is going away. http.Server.Shutdown then waits for a handler that has no way of knowing it should stop, until its own deadline expires, and returns with the connection still open.
A nil channel blocks forever in a select, which is the behaviour a handler wants when there is no server to shut down.
Reach it from a handler through Context.ShuttingDown rather than calling this directly.
Types ¶
type IPRange ¶
type IPRange struct {
Start string `ini:"start" json:"start" yaml:"Start" toml:"Start"`
End string `ini:"end" json:"end" yaml:"End" toml:"End"`
}
IPRange is a structure that holds the start and end of a range of IP Addresses.
type LimitsOptions ¶
type LimitsOptions struct {
// MaxHeaderBytes controls the maximum number of bytes the server will
// read parsing the request header's keys and values, including the
// request line. It does not limit the size of the request body.
//
// A zero value keeps the standard library's DefaultMaxHeaderBytes (1MB).
MaxHeaderBytes int `ini:"max_header_bytes" json:"max_header_bytes,omitzero" yaml:"MaxHeaderBytes" toml:"MaxHeaderBytes"`
// MaxHeaderValueCount controls the maximum number of header values
// a request may contain for any single header name. Since Go 1.27 the
// server responds with 400 Bad Request when a client exceeds it, which
// guards against repeated-header floods; set this field only to loosen
// or tighten that guard.
//
// A zero value keeps the standard library's DefaultMaxHeaderValueCount.
MaxHeaderValueCount int `ini:"max_header_value_count" json:"max_header_value_count,omitzero" yaml:"MaxHeaderValueCount" toml:"MaxHeaderValueCount"`
// DisableClientPriority opts out of RFC 9218 client-specified response
// prioritization on HTTP/2 connections. Every TLS Iris server offers "h2",
// so since Go 1.27 this scheduling is active by default; disable it when
// clients must not influence the order responses are written in.
DisableClientPriority bool `` /* 127-byte string literal not displayed */
}
LimitsOptions is used to configure the underline net/http server's request limits.
These matter more since Go 1.27: every TLS-enabled Iris server offers "h2" through its tls.Config NextProtos, and the HTTP/2 server now honors RFC 9218 client-driven response prioritization on every h2 connection unless DisableClientPriority is set. In the same release the server started rejecting, with a 400, requests that repeat a header name more times than MaxHeaderValueCount allows.
Its fields default to 0 (or false), which keeps the standard library's defaults. See the `LimitsOptions.ApplyToServer` method and the `ServerOptions.Limits` field.
func (*LimitsOptions) ApplyToServer ¶
func (c *LimitsOptions) ApplyToServer(srv *http.Server)
ApplyToServer sets the limits to the given standard http.Server instance, respecting any customization already made to the server: a field is written only when the option is set (non-zero or true) and the server's own field still holds its zero value.
type NgrokListenerFunc ¶
type NgrokListenerFunc func(ctx context.Context, opts *NgrokOptions, hostPatterns []string, addr string) (NgrokTunnelListener, error)
NgrokListenerFunc creates the listener of a ngrok tunnel for the given options. The package github.com/kataras/iris/v14/core/server/ngrok provides the implementation and registers it with RegisterNgrokListener.
It returns a NgrokTunnelListener and not a plain net.Listener, so the server always learns the public URL of the tunnel: it logs that URL at startup and adds its host to the allowed hosts.
func RegisteredNgrokListener ¶
func RegisteredNgrokListener() NgrokListenerFunc
RegisteredNgrokListener returns the function set by RegisterNgrokListener, or nil when the core/server/ngrok package is not linked in.
type NgrokOptions ¶
type NgrokOptions struct {
// Region is the ngrok region to connect to, e.g. "eu".
// It is not read by the server at the moment, the ngrok agent selects the region on its own.
Region string `json:"region,omitempty" yaml:"Region,omitempty" toml:"Region,omitempty"`
AuthToken string `json:"auth_token,omitempty" yaml:"AuthToken,omitempty" toml:"AuthToken,omitempty"` // if this is empty ngrok.WithAuthtokenFromEnv() is used.
// Compression enables compression streaming between ngrok, request body and server.
// Do not enable it if you are already enabled compression inside Iris application.
Compression bool `json:"compression,omitzero" yaml:"Compression,omitempty" toml:"Compression,omitempty"`
Oauth map[string]string `json:"oauth,omitempty" yaml:"Oauth,omitempty" toml:"Oauth,omitempty"` // config.WithOAuth("google", config.WithAllowOAuthDomain("example.com")) // key -> value.
}
NgrokOptions provides configuration for ngrok.
The tunnel code lives in its own package, so a program that sets these options also needs the blank import _ "github.com/kataras/iris/v14/core/server/ngrok".
The tunnel's domain is the first entry of the ServerOptions.Hosts, if it exists and it is not a loopback address, otherwise ngrok picks a random one.
type NgrokTunnelListener ¶
NgrokTunnelListener is the listener a NgrokListenerFunc returns. URL is the public URL of the tunnel and must not be nil.
type SSHTunnelOptions ¶
type SSHTunnelOptions struct {
// RemotePort is the port on the remote server to expose (e.g. 80 for HTTP).
RemotePort int `json:"remote_port" yaml:"RemotePort"`
// LocalHost is the local host to forward traffic to (e.g. "localhost").
LocalHost string `json:"local_host" yaml:"LocalHost"`
// LocalPort is the local port to forward traffic to (e.g. 8080).
LocalPort int `json:"local_port" yaml:"LocalPort"`
// Domain is the remote SSH server or custom subdomain/domain (e.g. "serveo.net" or "myapp.serveo.net").
Domain string `json:"domain,omitempty" yaml:"Domain,omitempty"`
// User is the SSH username (optional).
User string `json:"user,omitempty" yaml:"User,omitempty"`
// SSHKeyPath is the path to the SSH private key file (optional).
SSHKeyPath string `json:"ssh_key_path,omitempty" yaml:"SSHKeyPath,omitempty"`
// ExtraArgs allows specifying additional SSH command-line arguments.
ExtraArgs []string `json:"extra_args,omitempty" yaml:"ExtraArgs,omitempty"`
}
SSHTunnelOptions provides configuration for establishing an SSH reverse tunnel using services like serveo.net, localhost.run, or any SSH server that supports -R.
Example usage:
opts := SSHTunnelOptions{
RemotePort: 80, // Remote port to expose (e.g. 80 for HTTP).
LocalHost: "localhost", // Local host to forward to.
LocalPort: 8080, // Local port to forward to.
Domain: "serveo.net", // Remote SSH server (e.g. serveo.net, localhost.run).
User: "", // Optional: SSH username.
SSHKeyPath: "", // Optional: path to SSH private key.
ExtraArgs: []string{}, // Optional: additional SSH arguments.
}
The resulting SSH command would look like:
ssh -T [-i <SSHKeyPath>] -R <RemotePort>:<LocalHost>:<LocalPort> [extra args] [user@]<domain>
func (*SSHTunnelOptions) BuildCommand ¶
func (opts *SSHTunnelOptions) BuildCommand() string
BuildCommand returns the SSH command string for the SSHTunnelOptions. Example output: ssh -T -R 80:localhost:8080 serveo.net.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a simple HTTP server. It's a rich-featured wrapper around the standard http.Server. It provides a way to gracefully shutdown the server through the `Shutdown` method and to force-close it through the `Close` method. Closers of other resources are not registered here, they belong to the Iris Application (see its AddCloser method). It provides letsencrypt, ngrok, tls, and other options to configure the server, automatically handles host whitelist. It supports socket sharding for linear scaling of server performance on multi-CPU servers and many more.
func NewServer ¶
func NewServer(options ServerOptions) *Server
NewServer returns a new server instance. It does not start the server. Use the `ListenAndServe` method to start the server. Use the `Shutdown` method to shutdown the server. Use the `Close` method to immediately close the server. Use the `String` method to get the server's URL.
func (*Server) Close ¶
Close immediately closes all active connections. For a graceful shutdown, use the `Shutdown` method.
func (*Server) ListenAndServe ¶
ListenAndServe listens on the TCP network address and then calls Serve to handle requests on incoming connections.
It blocks until the server stops. After a Shutdown or a Close it returns nil, and only once that call has returned: a graceful shutdown has drained the requests in flight, or reached the deadline of its context, by then.
This is the server's own shutdown. iris.Application.Run waits for more: the closers that iris.Application.Shutdown runs after it.
func (*Server) OnListenerCreated ¶
OnListenerCreated sets a callback which is called when the server starts and the listener is created.
func (*Server) Shutdown ¶
Shutdown gracefully shuts down the server without interrupting any active connections. It waits for the requests in flight until ctx is done, then closes the connections that are left. ListenAndServe returns once Shutdown has returned.
A handler that stops its own server calls Shutdown on another goroutine, with a context of its own: go s.Shutdown(context.Background()), or one that carries a deadline. Called in place, Shutdown waits for the request that called it:
- with a context that has no deadline it does not return, and ListenAndServe waits with it. The request's own context is one of those: it ends only when the client goes away.
- with a deadline it returns at the deadline, after closing every connection that is left, the caller's own included.
The request's own context is no better on another goroutine: it is canceled when the handler returns, which closes the other connections at once.
func (*Server) String ¶
String returns the server's URL. It's empty until the server is started. It's safe to call it concurrently with ListenAndServe.
func (*Server) Wait ¶
Wait blocks until the server is up and running. If the server is already up and running it returns immediately. If the server is not running, it will retry to connect to the server with an exponential backoff. The context can be used to cancel the wait operation. If the server errors before it is up and running, the error is returned.
This is useful when you want to start the server on a separate go routine and wait somewhere else for it to be up and running before continuing. Useful also inside unit testing, so you don't have to use time.Sleep to wait for the server to be up and running before sending requests.
type ServerOptions ¶
type ServerOptions struct {
// The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket".
//
// Defaults to "tcp".
Network string `json:"network,omitempty" yaml:"Network,omitempty" toml:"Network,omitempty"`
// The address has the form "host:port".
// The host must be a literal IP address, or a host name that can be
// resolved to IP addresses.
// The port must be a literal port number or a service name.
// If the host is a literal IPv6 address it must be enclosed in square
// brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80".
//
// If Addr is an empty string, ":http" is used unless TLSConfig is provided, in which case
// it will be ":https".
Addr string `json:"addr,omitempty" yaml:"Addr,omitempty" toml:"Addr,omitempty"`
// KeepAlive specifies the keep-alive period for network
// connections accepted by this listener.
// If zero, keep-alives are enabled if supported by the protocol
// and operating system. Network protocols or operating systems
// that do not support keep-alives ignore this field.
// If negative, keep-alives are disabled.
KeepAlive time.Duration `json:"keep_alive,omitzero" yaml:"KeepAlive" toml:"keep_alive,omitempty"`
// SocketSharding enables SO_REUSEPORT (or SO_REUSEADDR on Windows).
// Allowing for linear scaling of server performance on multi-CPU servers.
// Defaults to false.
SocketSharding bool `json:"socket_sharding,omitzero" yaml:"SocketSharding,omitempty" toml:"SocketSharding,omitempty"`
// Hosts is the list of hosts that the certificate is valid for.
// If this is empty, the Application's Host will be used, if that is empty too,
// then the resolved host from Addr will be used instead.
// Framework should provide the root host and all subdomains registered (+.$FRAMEWORK_HOST),
// if a wildcard is used, then add (+.FRAMEWORK_HOST) it too.
// The first entry is expected to be the root domain, will be used on services like letsencrypt.
Hosts []string `json:"hosts,omitempty" yaml:"Hosts,omitempty" toml:"Hosts,omitempty"`
// TLSConfig optionally provides a TLS configuration for use.
// If this is set then LetsEncrypt and Ngrok and CertFile and KeyFile options SHOULD be nil.
TLSConfig *tls.Config `json:"-" yaml:"-" toml:"-"`
// CertFile and KeyFile are the paths to the TLS certificate and key files.
// The file must contain PEM encoded data.
CertFile string `json:"cert_file,omitempty" yaml:"CertFile,omitempty" toml:"CertFile,omitempty"`
// KeyFile is the path to the TLS key file.
// The file must contain PEM encoded data.
KeyFile string `json:"key_file,omitempty" yaml:"KeyFile,omitempty" toml:"KeyFile,omitempty"`
// Letsencrypt enables automatic HTTPS certificates from Let's Encrypt.
// A host is validated with the tls-alpn-01 challenge, which this TLS listener answers itself:
// Let's Encrypt connects to port 443 of the host, so that port must reach this server.
// The HTTP-01 challenge is not served, so no handler on port 80 is involved.
// If this is enabled but custom CertFile and KeyFile are provided then they are used as a fallback if Let's Encrypt fails,
// useful for local testing. Nothing is logged when the fallback pair is served.
Letsencrypt bool `json:"letsencrypt,omitzero" yaml:"Letsencrypt,omitempty" toml:"Letsencrypt,omitempty"`
// Ngrok provides a tunnel to the local server. If this is set then TLSConfig, Letsencrypt, CertFile and KeyFile options SHOULD be nil.
// It needs the blank import _ "github.com/kataras/iris/v14/core/server/ngrok" somewhere in the program: without it the server fails to start.
Ngrok *NgrokOptions `json:"ngrok,omitempty" yaml:"Ngrok,omitempty" toml:"Ngrok,omitempty"`
// SSHTunnel enables SSH reverse tunnel, if set then TLSConfig, Letsencrypt, CertFile and KeyFile and Ngrok options SHOULD be nil.
SSHTunnel *SSHTunnelOptions `json:"ssh_tunnel,omitempty" yaml:"SSHTunnel,omitempty" toml:"SSHTunnel,omitempty"`
// Timeout server and router(main handler) configuration.
Timeout *TimeoutOptions `json:"timeout,omitempty" yaml:"Timeout,omitempty" toml:"Timeout,omitempty"`
// Limits configures the underline net/http server's request limits.
// Worth a look since Go 1.27: every TLS Iris server offers "h2", so RFC 9218
// client-driven response prioritization is on by default (see DisableClientPriority),
// and MaxHeaderValueCount guards the new repeated-header 400 default.
Limits *LimitsOptions `json:"limits,omitempty" yaml:"Limits,omitempty" toml:"Limits,omitempty"`
// OnServerCreated is called with the standard http.Server instance right after
// it's created and the Timeout and Limits options are applied to it, and before
// it starts serving. It is the escape hatch for any http.Server field Iris does
// not mirror as an option — including fields added by future Go releases — and
// for TLS knobs on its TLSConfig such as CurvePreferences (e.g. tls.MLKEM1024;
// Go's default curve preferences already include the post-quantum hybrid, which
// is why Iris deliberately leaves CurvePreferences nil).
// If it returns a non-nil error the listener is closed and the server does not start.
OnServerCreated func(*http.Server) error `json:"-" yaml:"-" toml:"-"`
// LogWriter is the logger that the server should use when errors are propagated from the standard library's http.Server instance.
// If nil, logging is done via the log package's standard logger. This only applies to errors that are not related to the request.
LogWriter io.Writer `json:"-" yaml:"-" toml:"-"`
// DisableStartupLog disables the startup log message when server starts.
DisableStartupLog bool `json:"disable_startup_log,omitzero" yaml:"DisableStartupLog,omitempty" toml:"DisableStartupLog,omitempty"`
// DisableInterruptHandler disables the interrupt handler, if true then the server will not wait for the interrupt signal to shutdown and cleanup.
DisableInterruptHandler bool `json:"disable_interrupt_handler,omitzero" yaml:"DisableInterruptHandler,omitempty" toml:"DisableInterruptHandler,omitempty"`
// contains filtered or unexported fields
}
ServerOptions is the configuration for the server. It's used to configure the server's network address, timeouts, TLS, LetsEncrypt, Ngrok, and other options. See "NewServer" package-level function for more.
func (*ServerOptions) IsTLS ¶
func (opts *ServerOptions) IsTLS() bool
IsTLS checks if the server is configured to use TLS.
func (*ServerOptions) PrependHostPatterns ¶
func (opts *ServerOptions) PrependHostPatterns(patterns ...string)
PrependHostPatterns prepends the host patterns to the server's hosts option. Has no effect after the server starts.
type TimeoutOptions ¶
type TimeoutOptions struct {
// ShutdownOnInterruptTimeout is the maximum duration for the server to wait for
// the server to shutdown on OS interrupt signal (e.g. CTRL+C).
// A zero or negative value means there will be no timeout: the server waits
// for every request in flight, however long that takes.
//
// The `Timeout` function sets it to 15 seconds, and a server whose Timeout
// option is nil gets the same. A TimeoutOptions literal, or a configuration
// file whose Timeout section leaves the field out, carries zero.
ShutdownOnInterruptTimeout time.Duration `` /* 149-byte string literal not displayed */
// ServerTimeout is the underline net/http server's read/write timeout.
// if greater than zero, framework automatically calculates and sets the server's read headers,
// idle connection and write timeouts. We don't automatically set the read timeout (which includes the read body timeout),
// in order for handlers to decide by theirselves (e.g. big file upload and/or slow clients).
// Follow up with the fields below to learn more about these timeouts.
ServerTimeout time.Duration `ini:"server_timeout" json:"server_timeout,omitzero" yaml:"ServerTimeout" toml:"ServerTimeout"`
// ReadTimeout is the maximum duration for reading the entire
// request, including the body. A zero or negative value means
// there will be no timeout.
//
// Because ReadTimeout does not let Handlers make per-request
// decisions on each request body's acceptable deadline or
// upload rate, most users will prefer to use
// ReadHeaderTimeout. It is valid to use them both.
ReadTimeout time.Duration `ini:"read_timeout" json:"read_timeout,omitzero" yaml:"ReadTimeout" toml:"ReadTimeout"`
// ReadHeaderTimeout is the amount of time allowed to read
// request headers. The connection's read deadline is reset
// after reading the headers and the Handler can decide what
// is considered too slow for the body. If ReadHeaderTimeout
// is zero, the value of ReadTimeout is used. If both are
// zero, there is no timeout.
ReadHeaderTimeout time.Duration `ini:"read_header_timeout" json:"read_header_timeout,omitzero" yaml:"ReadHeaderTimeout" toml:"ReadHeaderTimeout"`
// WriteTimeout is the maximum duration before timing out
// writes of the response. It is reset whenever a new
// request's header is read. Like ReadTimeout, it does not
// let Handlers make decisions on a per-request basis.
// A zero or negative value means there will be no timeout.
WriteTimeout time.Duration `ini:"write_timeout" json:"write_timeout,omitzero" yaml:"WriteTimeout" toml:"WriteTimeout"`
// IdleTimeout is the maximum amount of time to wait for the
// next request when keep-alives are enabled. If IdleTimeout
// is zero, the value of ReadTimeout is used. If both are
// zero, there is no timeout.
IdleTimeout time.Duration `ini:"idle_timeout" json:"idle_timeout,omitzero" yaml:"IdleTimeout" toml:"IdleTimeout"`
// HandlerTimeout wraps the application's router with an http timeout handler
// if the value is greater than zero.
// It wraps the router (except when Downgrade is used) under the standard net/http.TimeoutHandler.
//
// The underline response writer supports the Pusher interface but does not support
// the Hijacker or Flusher interfaces when Timeout handler is registered.
//
// Read more at: https://pkg.go.dev/net/http#TimeoutHandler.
//
// See the `HandlerTimeoutMessage` field to customize the displayed message too.
HandlerTimeout time.Duration `ini:"handler_timeout" json:"handler_timeout,omitzero" yaml:"HandlerTimeout" toml:"HandlerTimeout"`
// HandlerTimeoutMessage is the message (HTML) to be sent when the handler's timeout reached.
HandlerTimeoutMessage string `` /* 128-byte string literal not displayed */
}
TimeoutOptions is used to configure the server's timeouts.
The right timeouts for an HTTP lifecycle decide how the server behaves under load and how quickly a stuck client is released. Some general guidelines:
Read Headers Timeout: This should be relatively short, as header data is typically small and quick to transmit. A common timeout is between 1-5 seconds. Read Timeout: This depends on the expected size of the body content and headers.
For small to medium-sized bodies, 5-10 seconds might be sufficient. For larger bodies, especially if you expect large file uploads, you might need to increase this to 30 seconds or more.
Idle Connection Timeout: This is the time a connection stays open waiting for new requests. Common values range from 5 seconds to 120 seconds1. Apache’s default, for example, is 5 seconds. Server Write Timeout: This is the time your server will try to send a response. This can be similar to the read body timeout, but you might want to allow extra time in case of slow clients. A starting point could be 10 seconds.
Its fields default to 0. Initialize a new timeout configuration through the `Timeout` package-level function.
func Timeout ¶
func Timeout() *TimeoutOptions
Timeout returns a new TimeoutOptions, as it works as a builder.
func (*TimeoutOptions) ApplyToServer ¶
func (c *TimeoutOptions) ApplyToServer(srv *http.Server)
func (*TimeoutOptions) Get ¶
func (c *TimeoutOptions) Get() *TimeoutOptions
Get returns the TimeoutOptions itself if it's not nil, otherwise it returns the default TimeoutOptions.
func (*TimeoutOptions) TimeoutHandler ¶
func (c *TimeoutOptions) TimeoutHandler(mainHandler http.Handler) http.Handler
func (*TimeoutOptions) WithHandlerTimeout ¶
func (c *TimeoutOptions) WithHandlerTimeout(timeout time.Duration, htmlBody ...string) *TimeoutOptions
func (*TimeoutOptions) WithIdleTimeout ¶
func (c *TimeoutOptions) WithIdleTimeout(timeout time.Duration) *TimeoutOptions
WithIdleTimeout sets the server's idle connection timeout.
func (*TimeoutOptions) WithReadHeaderTimeout ¶
func (c *TimeoutOptions) WithReadHeaderTimeout(timeout time.Duration) *TimeoutOptions
WithReadHeaderTimeout sets the server's read headers timeout.
func (*TimeoutOptions) WithReadTimeout ¶
func (c *TimeoutOptions) WithReadTimeout(timeout time.Duration) *TimeoutOptions
WithReadTimeout sets the server's read headers and body timeout.
func (*TimeoutOptions) WithServerTimeout ¶
func (c *TimeoutOptions) WithServerTimeout(timeout time.Duration) *TimeoutOptions
WithServerTimeout sets the server's read/write timeout. Overrides the read header, idle connection and write timeouts if they are not set. The read (body) timeout is deliberately left alone, so handlers can decide by theirselves (e.g. big file upload and/or slow clients); use the `WithReadTimeout` method to set it.
func (*TimeoutOptions) WithShutdownOnInterruptTimeout ¶
func (c *TimeoutOptions) WithShutdownOnInterruptTimeout(timeout time.Duration) *TimeoutOptions
WithShutdownOnInterruptTimeout sets the maximum duration for the server to wait for the server to shutdown on OS interrupt signal (e.g. CTRL+C). A zero or negative value means there will be no timeout.
The options the `Timeout` function returns start at 15 seconds.
func (*TimeoutOptions) WithWriteTimeout ¶
func (c *TimeoutOptions) WithWriteTimeout(timeout time.Duration) *TimeoutOptions
WithWriteTimeout sets the server's write timeout.