kenginehttp

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2024 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type App

type App struct {
	// HTTPPort specifies the port to use for HTTP (as opposed to HTTPS),
	// which is used when setting up HTTP->HTTPS redirects or ACME HTTP
	// challenge solvers. Default: 80.
	HTTPPort int `json:"http_port,omitempty"`

	// HTTPSPort specifies the port to use for HTTPS, which is used when
	// solving the ACME TLS-ALPN challenges, or whenever HTTPS is needed
	// but no specific port number is given. Default: 443.
	HTTPSPort int `json:"https_port,omitempty"`

	// GracePeriod is how long to wait for active connections when shutting
	// down the servers. During the grace period, no new connections are
	// accepted, idle connections are closed, and active connections will
	// be given the full length of time to become idle and close.
	// Once the grace period is over, connections will be forcefully closed.
	// If zero, the grace period is eternal. Default: 0.
	GracePeriod kengine.Duration `json:"grace_period,omitempty"`

	// ShutdownDelay is how long to wait before initiating the grace
	// period. When this app is stopping (e.g. during a config reload or
	// process exit), all servers will be shut down. Normally this immediately
	// initiates the grace period. However, if this delay is configured, servers
	// will not be shut down until the delay is over. During this time, servers
	// continue to function normally and allow new connections. At the end, the
	// grace period will begin. This can be useful to allow downstream load
	// balancers time to move this instance out of the rotation without hiccups.
	//
	// When shutdown has been scheduled, placeholders {http.shutting_down} (bool)
	// and {http.time_until_shutdown} (duration) may be useful for health checks.
	ShutdownDelay kengine.Duration `json:"shutdown_delay,omitempty"`

	// Servers is the list of servers, keyed by arbitrary names chosen
	// at your discretion for your own convenience; the keys do not
	// affect functionality.
	Servers map[string]*Server `json:"servers,omitempty"`
}

App is a robust, production-ready HTTP server.

HTTPS is enabled by default if host matchers with qualifying names are used in any of routes; certificates are automatically provisioned and renewed. Additionally, automatic HTTPS will also enable HTTPS for servers that listen only on the HTTPS port but which do not have any TLS connection policies defined by adding a good, default TLS connection policy.

In HTTP routes, additional placeholders are available (replace any `*`):

Placeholder | Description ------------|--------------- `{http.request.body}` | The request body (⚠️ inefficient; use only for debugging) `{http.request.cookie.*}` | HTTP request cookie `{http.request.duration}` | Time up to now spent handling the request (after decoding headers from client) `{http.request.duration_ms}` | Same as 'duration', but in milliseconds. `{http.request.uuid}` | The request unique identifier `{http.request.header.*}` | Specific request header field `{http.request.host}` | The host part of the request's Host header `{http.request.host.labels.*}` | Request host labels (0-based from right); e.g. for foo.example.com: 0=com, 1=example, 2=foo `{http.request.hostport}` | The host and port from the request's Host header `{http.request.method}` | The request method `{http.request.orig_method}` | The request's original method `{http.request.orig_uri}` | The request's original URI `{http.request.orig_uri.path}` | The request's original path `{http.request.orig_uri.path.*}` | Parts of the original path, split by `/` (0-based from left) `{http.request.orig_uri.path.dir}` | The request's original directory `{http.request.orig_uri.path.file}` | The request's original filename `{http.request.orig_uri.query}` | The request's original query string (without `?`) `{http.request.port}` | The port part of the request's Host header `{http.request.proto}` | The protocol of the request `{http.request.remote.host}` | The host (IP) part of the remote client's address `{http.request.remote.port}` | The port part of the remote client's address `{http.request.remote}` | The address of the remote client `{http.request.scheme}` | The request scheme, typically `http` or `https` `{http.request.tls.version}` | The TLS version name `{http.request.tls.cipher_suite}` | The TLS cipher suite `{http.request.tls.resumed}` | The TLS connection resumed a previous connection `{http.request.tls.proto}` | The negotiated next protocol `{http.request.tls.proto_mutual}` | The negotiated next protocol was advertised by the server `{http.request.tls.server_name}` | The server name requested by the client, if any `{http.request.tls.client.fingerprint}` | The SHA256 checksum of the client certificate `{http.request.tls.client.public_key}` | The public key of the client certificate. `{http.request.tls.client.public_key_sha256}` | The SHA256 checksum of the client's public key. `{http.request.tls.client.certificate_pem}` | The PEM-encoded value of the certificate. `{http.request.tls.client.certificate_der_base64}` | The base64-encoded value of the certificate. `{http.request.tls.client.issuer}` | The issuer DN of the client certificate `{http.request.tls.client.serial}` | The serial number of the client certificate `{http.request.tls.client.subject}` | The subject DN of the client certificate `{http.request.tls.client.san.dns_names.*}` | SAN DNS names(index optional) `{http.request.tls.client.san.emails.*}` | SAN email addresses (index optional) `{http.request.tls.client.san.ips.*}` | SAN IP addresses (index optional) `{http.request.tls.client.san.uris.*}` | SAN URIs (index optional) `{http.request.uri}` | The full request URI `{http.request.uri.path}` | The path component of the request URI `{http.request.uri.path.*}` | Parts of the path, split by `/` (0-based from left) `{http.request.uri.path.dir}` | The directory, excluding leaf filename `{http.request.uri.path.file}` | The filename of the path, excluding directory `{http.request.uri.query}` | The query string (without `?`) `{http.request.uri.query.*}` | Individual query string value `{http.response.header.*}` | Specific response header field `{http.vars.*}` | Custom variables in the HTTP handler chain `{http.shutting_down}` | True if the HTTP app is shutting down `{http.time_until_shutdown}` | Time until HTTP server shutdown, if scheduled

type AutoHTTPSConfig

type AutoHTTPSConfig struct {
	// If true, automatic HTTPS will be entirely disabled,
	// including certificate management and redirects.
	Disabled bool `json:"disable,omitempty"`

	// If true, only automatic HTTP->HTTPS redirects will
	// be disabled, but other auto-HTTPS features will
	// remain enabled.
	DisableRedir bool `json:"disable_redirects,omitempty"`

	// If true, automatic certificate management will be
	// disabled, but other auto-HTTPS features will
	// remain enabled.
	DisableCerts bool `json:"disable_certificates,omitempty"`

	// Hosts/domain names listed here will not be included
	// in automatic HTTPS (they will not have certificates
	// loaded nor redirects applied).
	Skip []string `json:"skip,omitempty"`

	// Hosts/domain names listed here will still be enabled
	// for automatic HTTPS (unless in the Skip list), except
	// that certificates will not be provisioned and managed
	// for these names.
	SkipCerts []string `json:"skip_certificates,omitempty"`

	// By default, automatic HTTPS will obtain and renew
	// certificates for qualifying hostnames. However, if
	// a certificate with a matching SAN is already loaded
	// into the cache, certificate management will not be
	// enabled. To force automated certificate management
	// regardless of loaded certificates, set this to true.
	IgnoreLoadedCerts bool `json:"ignore_loaded_certificates,omitempty"`
}

AutoHTTPSConfig is used to disable automatic HTTPS or certain aspects of it for a specific server. HTTPS is enabled automatically and by default when qualifying hostnames are available from the config.

type HTTPErrorConfig

type HTTPErrorConfig struct {
	// The routes to evaluate after the primary handler
	// chain returns an error. In an error route, extra
	// placeholders are available:
	//
	// Placeholder | Description
	// ------------|---------------
	// `{http.error.status_code}` | The recommended HTTP status code
	// `{http.error.status_text}` | The status text associated with the recommended status code
	// `{http.error.message}`     | The error message
	// `{http.error.trace}`       | The origin of the error
	// `{http.error.id}`          | An identifier for this occurrence of the error
	Routes []Route `json:"routes,omitempty"`
}

HTTPErrorConfig determines how to handle errors from the HTTP handlers.

type HTTPRedirectListenerWrapper

type HTTPRedirectListenerWrapper struct {
	// Wrapper is the name of this wrapper for the JSON config.
	// DO NOT USE this. This is a special value to represent this wrapper.
	// It will be overwritten when we are marshalled.
	Wrapper HTTPRedirectListenerWrapperName `json:"wrapper"`

	// MaxHeaderBytes is the maximum size to parse from a client's
	// HTTP request headers. Default: 1 MB
	MaxHeaderBytes int64 `json:"max_header_bytes,omitempty"`
}

HTTPRedirectListenerWrapper provides HTTP->HTTPS redirects for connections that come on the TLS port as an HTTP request, by detecting using the first few bytes that it's not a TLS handshake, but instead an HTTP request.

This is especially useful when using a non-standard HTTPS port. A user may simply type the address in their browser without the https:// scheme, which would cause the browser to attempt the connection over HTTP, but this would cause a "Client sent an HTTP request to an HTTPS server" error response.

This listener wrapper must be placed BEFORE the "tls" listener wrapper, for it to work properly.

type HTTPRedirectListenerWrapperName

type HTTPRedirectListenerWrapperName string

func (HTTPRedirectListenerWrapperName) MarshalJSON

func (HTTPRedirectListenerWrapperName) MarshalJSON() ([]byte, error)

type Handler

type Handler interface {
	IAmAHandler()
}

type ListenerWrapper

type ListenerWrapper struct {
	// HTTPRedirect .
	// TODO: document
	// ref; https://khulnasoft.com/docs/json/apps/http/servers/listener_wrappers/http_redirect/
	HTTPRedirect *HTTPRedirectListenerWrapper `json:"http_redirect,omitempty"`

	// TLS .
	// TODO: document
	// ref; https://khulnasoft.com/docs/json/apps/http/servers/listener_wrappers/tls/
	TLS *TLSListenerWrapper `json:"tls,omitempty"`

	// ProxyProtocol .
	// TODO: document
	// ref; https://khulnasoft.com/docs/json/apps/http/servers/listener_wrappers/proxy_protocol/
	ProxyProtocol *proxyprotocol.ListenerWrapper `json:"proxy_protocol,omitempty"`
}

ListenerWrapper . TODO: document ref; https://khulnasoft.com/docs/json/apps/http/servers/listener_wrappers/

type ListenerWrappers

type ListenerWrappers []ListenerWrapper

ListenerWrappers . TODO: document

type Match

type Match struct {
	ClientIP   *MatchClientIP   `json:"client_ip,omitempty"`
	Expression *MatchExpression `json:"expression,omitempty"`
	Header     MatchHeader      `json:"header,omitempty"`
	HeaderRE   MatchHeaderRE    `json:"header_regexp,omitempty"`
	Host       MatchHost        `json:"host,omitempty"`
	Method     MatchMethod      `json:"method,omitempty"`
	Not        *MatchNot        `json:"not,omitempty"`
	Path       MatchPath        `json:"path,omitempty"`
	PathRE     *MatchPathRE     `json:"path_regexp,omitempty"`
	Protocol   MatchProtocol    `json:"protocol,omitempty"`
	Query      MatchQuery       `json:"query,omitempty"`
	RemoteIP   *MatchRemoteIP   `json:"remote_ip,omitempty"`
	Vars       MatchVars        `json:"vars,omitempty"`
	VarsRE     MatchVarsRE      `json:"vars_regexp,omitempty"`
}

Match . TODO: document

func (*Match) IsEmpty

func (m *Match) IsEmpty() bool

type MatchClientIP

type MatchClientIP struct {
	// The IPs or CIDR ranges to match.
	Ranges []string `json:"ranges,omitempty"`
}

MatchClientIP matches requests by the client IP address, i.e. the resolved address, considering trusted proxies.

type MatchExpression

type MatchExpression struct {
	// The CEL expression to evaluate. Any Kengine placeholders
	// will be expanded and situated into proper CEL function
	// calls before evaluating.
	Expr string
}

MatchExpression matches requests by evaluating a [CEL](https://github.com/google/cel-spec) expression. This enables complex logic to be expressed using a comfortable, familiar syntax. Please refer to [the standard definitions of CEL functions and operators](https://github.com/google/cel-spec/blob/master/doc/langdef.md#standard-definitions).

This matcher's JSON interface is actually a string, not a struct. The generated docs are not correct because this type has custom marshaling logic.

COMPATIBILITY NOTE: This module is still experimental and is not subject to Kengine's compatibility guarantee.

func (MatchExpression) MarshalJSON

func (m MatchExpression) MarshalJSON() ([]byte, error)

type MatchHeader

type MatchHeader http.Header

MatchHeader matches requests by header fields. The key is the field name and the array is the list of field values. It performs fast, exact string comparisons of the field values. Fast prefix, suffix, and substring matches can also be done by suffixing, prefixing, or surrounding the value with the wildcard `*` character, respectively. If a list is null, the header must not exist. If the list is empty, the field must simply exist, regardless of its value.

**NOTE:** Notice that header values are arrays, not singular values. This is because repeated fields are valid in headers, and each one may have a different value. This matcher will match for a field if any one of its configured values matches in the header. Backend applications relying on headers MUST take into consideration that header field values are arrays and can have multiple values.

type MatchHeaderRE

type MatchHeaderRE map[string]*MatchRegexp

MatchHeaderRE matches requests by a regular expression on header fields.

Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` where `name` is the regular expression's name, and `capture_group` is either the named or positional capture group from the expression itself. If no name is given, then the placeholder omits the name: `{http.regexp.capture_group}` (potentially leading to collisions).

type MatchHost

type MatchHost []string

MatchHost matches requests by the Host value (case-insensitive).

When used in a top-level HTTP route, [qualifying domain names](/docs/automatic-https#hostname-requirements) may trigger [automatic HTTPS](/docs/automatic-https), which automatically provisions and renews certificates for you. Before doing this, you should ensure that DNS records for these domains are properly configured, especially A/AAAA pointed at your server.

Automatic HTTPS can be [customized or disabled](/docs/modules/http#servers/automatic_https).

Wildcards (`*`) may be used to represent exactly one label of the hostname, in accordance with RFC 1034 (because host matchers are also used for automatic HTTPS which influences TLS certificates). Thus, a host of `*` matches hosts like `localhost` or `internal` but not `example.com`. To catch all hosts, omit the host matcher entirely.

The wildcard can be useful for matching all subdomains, for example: `*.example.com` matches `foo.example.com` but not `foo.bar.example.com`.

Duplicate entries will return an error.

type MatchMethod

type MatchMethod []string

MatchMethod matches requests by the method.

type MatchNot

type MatchNot struct {
	MatcherSets []Match `json:"-"`
}

MatchNot matches requests by negating the results of its matcher sets. A single "not" matcher takes one or more matcher sets. Each matcher set is OR'ed; in other words, if any matcher set returns true, the final result of the "not" matcher is false. Individual matchers within a set work the same (i.e. different matchers in the same set are AND'ed).

where each of the array elements is a matcher set, i.e. an object keyed by matcher name.

func (MatchNot) MarshalJSON

func (m MatchNot) MarshalJSON() ([]byte, error)

type MatchPath

type MatchPath []string

MatchPath case-insensitively matches requests by the URI's path. Path matching is exact, not prefix-based, giving you more control and clarity over matching. Wildcards (`*`) may be used:

- At the end only, for a prefix match (`/prefix/*`) - At the beginning only, for a suffix match (`*.suffix`) - On both sides only, for a substring match (`*/contains/*`) - In the middle, for a globular match (`/accounts/*/info`)

Slashes are significant; i.e. `/foo*` matches `/foo`, `/foo/`, `/foo/bar`, and `/foobar`; but `/foo/*` does not match `/foo` or `/foobar`. Valid paths start with a slash `/`.

Because there are, in general, multiple possible escaped forms of any path, path matchers operate in unescaped space; that is, path matchers should be written in their unescaped form to prevent ambiguities and possible security issues, as all request paths will be normalized to their unescaped forms before matcher evaluation.

However, escape sequences in a match pattern are supported; they are compared with the request's raw/escaped path for those bytes only. In other words, a matcher of `/foo%2Fbar` will match a request path of precisely `/foo%2Fbar`, but not `/foo/bar`. It follows that matching the literal percent sign (%) in normalized space can be done using the escaped form, `%25`.

Even though wildcards (`*`) operate in the normalized space, the special escaped wildcard (`%*`), which is not a valid escape sequence, may be used in place of a span that should NOT be decoded; that is, `/bands/%*` will match `/bands/AC%2fDC` whereas `/bands/*` will not.

Even though path matching is done in normalized space, the special wildcard `%*` may be used in place of a span that should NOT be decoded; that is, `/bands/%*/` will match `/bands/AC%2fDC/` whereas `/bands/*/` will not.

This matcher is fast, so it does not support regular expressions or capture groups. For slower but more powerful matching, use the path_regexp matcher. (Note that due to the special treatment of escape sequences in matcher patterns, they may perform slightly slower in high-traffic environments.)

type MatchPathRE

type MatchPathRE struct {
	MatchRegexp
}

MatchPathRE matches requests by a regular expression on the URI's path. Path matching is performed in the unescaped (decoded) form of the path.

Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` where `name` is the regular expression's name, and `capture_group` is either the named or positional capture group from the expression itself. If no name is given, then the placeholder omits the name: `{http.regexp.capture_group}` (potentially leading to collisions).

type MatchProtocol

type MatchProtocol string

MatchProtocol matches requests by protocol. Recognized values are "http", "https", and "grpc" for broad protocol matches, or specific HTTP versions can be specified like so: "http/1", "http/1.1", "http/2", "http/3", or minimum versions: "http/2+", etc.

type MatchQuery

type MatchQuery url.Values

MatchQuery matches requests by the URI's query string. It takes a JSON object keyed by the query keys, with an array of string values to match for that key. Query key matches are exact, but wildcards may be used for value matches. Both keys and values may be placeholders.

An example of the structure to match `?key=value&topic=api&query=something` is:

```json

{
	"key": ["value"],
	"topic": ["api"],
	"query": ["*"]
}

```

Invalid query strings, including those with bad escapings or illegal characters like semicolons, will fail to parse and thus fail to match.

**NOTE:** Notice that query string values are arrays, not singular values. This is because repeated keys are valid in query strings, and each one may have a different value. This matcher will match for a key if any one of its configured values is assigned in the query string. Backend applications relying on query strings MUST take into consideration that query string values are arrays and can have multiple values.

type MatchRegexp

type MatchRegexp struct {
	// A unique name for this regular expression. Optional,
	// but useful to prevent overwriting captures from other
	// regexp matchers.
	Name string `json:"name,omitempty"`

	// The regular expression to evaluate, in RE2 syntax,
	// which is the same general syntax used by Go, Perl,
	// and Python. For details, see
	// [Go's regexp package](https://golang.org/pkg/regexp/).
	// Captures are accessible via placeholders. Unnamed
	// capture groups are exposed as their numeric, 1-based
	// index, while named capture groups are available by
	// the capture group name.
	Pattern string `json:"pattern"`
}

MatchRegexp is an embedable type for matching using regular expressions. It adds placeholders to the request's replacer.

type MatchRemoteIP

type MatchRemoteIP struct {
	// The IPs or CIDR ranges to match.
	Ranges []string `json:"ranges,omitempty"`
}

MatchRemoteIP matches requests by the remote IP address, i.e. the IP address of the direct connection to Kengine.

type MatchVars

type MatchVars map[string][]string

MatchVars is an HTTP request matcher which can match requests based on variables in the context or placeholder values. The key is the placeholder or name of the variable, and the values are possible values the variable can be in order to match (logical OR'ed).

If the key is surrounded by `{ }` it is assumed to be a placeholder. Otherwise, it will be considered a variable name.

Placeholders in the keys are not expanded, but placeholders in the values are.

type MatchVarsRE

type MatchVarsRE map[string]*MatchRegexp

MatchVarsRE matches the value of the context variables by a given regular expression.

Upon a match, it adds placeholders to the request: `{http.regexp.name.capture_group}` where `name` is the regular expression's name, and `capture_group` is either the named or positional capture group from the expression itself. If no name is given, then the placeholder omits the name: `{http.regexp.capture_group}` (potentially leading to collisions).

type Metrics

type Metrics struct{}

Metrics configures metrics observations. EXPERIMENTAL and subject to change or removal.

type ResponseHandler

type ResponseHandler struct {
	// The response matcher for this handler. If empty/nil,
	// it always matches.
	Match *ResponseMatcher `json:"match,omitempty"`

	// To write the original response body but with a different
	// status code, set this field to the desired status code.
	// If set, this takes priority over routes.
	StatusCode WeakString `json:"status_code,omitempty"`

	// The list of HTTP routes to execute if no status code is
	// specified. If evaluated, the original response body
	// will not be written.
	Routes []Route `json:"routes,omitempty"`
}

ResponseHandler pairs a response matcher with custom handling logic. Either the status code can be changed to something else while using the original response body, or, if a status code is not set, it can execute a custom route list; this is useful for executing handler routes based on the properties of an HTTP response that has not been written out to the client yet.

To use this type, provision it at module load time, then when ready to use, match the response against its matcher; if it matches (or doesn't have a matcher), change the status code on the response if configured; otherwise invoke the routes by calling `rh.Routes.Compile(next).ServeHTTP(rw, req)` (or similar).

type ResponseMatcher

type ResponseMatcher struct {
	// If set, one of these status codes would be required.
	// A one-digit status can be used to represent all codes
	// in that class (e.g. 3 for all 3xx codes).
	StatusCode []int `json:"status_code,omitempty"`

	// If set, each header specified must be one of the
	// specified values, with the same logic used by the
	// [request header matcher](/docs/json/apps/http/servers/routes/match/header/).
	Headers http.Header `json:"headers,omitempty"`
}

ResponseMatcher is a type which can determine if an HTTP response matches some criteria.

type Route

type Route struct {
	// Group is an optional name for a group to which this
	// route belongs. Grouping a route makes it mutually
	// exclusive with others in its group; if a route belongs
	// to a group, only the first matching route in that group
	// will be executed.
	Group string `json:"group,omitempty"`

	// The matcher sets which will be used to qualify this
	// route for a request (essentially the "if" statement
	// of this route). Each matcher set is OR'ed, but matchers
	// within a set are AND'ed together.
	MatcherSets []Match `json:"match,omitempty"`

	// The list of handlers for this route. Upon matching a request, they are chained
	// together in a middleware fashion: requests flow from the first handler to the last
	// (top of the list to the bottom), with the possibility that any handler could stop
	// the chain and/or return an error. Responses flow back through the chain (bottom of
	// the list to the top) as they are written out to the client.
	//
	// Not all handlers call the next handler in the chain. For example, the reverse_proxy
	// handler always sends a request upstream or returns an error. Thus, configuring
	// handlers after reverse_proxy in the same route is illogical, since they would never
	// be executed. You will want to put handlers which originate the response at the very
	// end of your route(s). The documentation for a module should state whether it invokes
	// the next handler, but sometimes it is common sense.
	//
	// Some handlers manipulate the response. Remember that requests flow down the list, and
	// responses flow up the list.
	//
	// For example, if you wanted to use both `templates` and `encode` handlers, you would
	// need to put `templates` after `encode` in your route, because responses flow up.
	// Thus, `templates` will be able to parse and execute the plain-text response as a
	// template, and then return it up to the `encode` handler which will then compress it
	// into a binary format.
	//
	// If `templates` came before `encode`, then `encode` would write a compressed,
	// binary-encoded response to `templates` which would not be able to parse the response
	// properly.
	//
	// The correct order, then, is this:
	//
	//     [
	//         {"handler": "encode"},
	//         {"handler": "templates"},
	//         {"handler": "file_server"}
	//     ]
	//
	// The request flows ⬇️ DOWN (`encode` -> `templates` -> `file_server`).
	//
	// 1. First, `encode` will choose how to `encode` the response and wrap the response.
	// 2. Then, `templates` will wrap the response with a buffer.
	// 3. Finally, `file_server` will originate the content from a file.
	//
	// The response flows ⬆️ UP (`file_server` -> `templates` -> `encode`):
	//
	// 1. First, `file_server` will write the file to the response.
	// 2. That write will be buffered and then executed by `templates`.
	// 3. Lastly, the write from `templates` will flow into `encode` which will compress the stream.
	//
	// If you think of routes in this way, it will be easy and even fun to solve the puzzle of writing correct routes.
	Handlers []Handler `json:"handle,omitempty"`

	// If true, no more routes will be executed after this one.
	Terminal bool `json:"terminal,omitempty"`
}

Route consists of a set of rules for matching HTTP requests, a list of handlers to execute, and optional flow control parameters which customize the handling of HTTP requests in a highly flexible and performant manner.

type Server

type Server struct {
	// Socket addresses to which to bind listeners. Accepts
	// [network addresses](/docs/conventions#network-addresses)
	// that may include port ranges. Listener addresses must
	// be unique; they cannot be repeated across all defined
	// servers.
	Listen []string `json:"listen,omitempty"`

	// A list of listener wrapper modules, which can modify the behavior
	// of the base listener. They are applied in the given order.
	ListenerWrappers ListenerWrappers `json:"listener_wrappers,omitempty"`

	// How long to allow a read from a client's upload. Setting this
	// to a short, non-zero value can mitigate slowloris attacks, but
	// may also affect legitimately slow clients.
	ReadTimeout kengine.Duration `json:"read_timeout,omitempty"`

	// ReadHeaderTimeout is like ReadTimeout but for request headers.
	ReadHeaderTimeout kengine.Duration `json:"read_header_timeout,omitempty"`

	// WriteTimeout is how long to allow a write to a client. Note
	// that setting this to a small value when serving large files
	// may negatively affect legitimately slow clients.
	WriteTimeout kengine.Duration `json:"write_timeout,omitempty"`

	// IdleTimeout is the maximum time to wait for the next request
	// when keep-alives are enabled. If zero, a default timeout of
	// 5m is applied to help avoid resource exhaustion.
	IdleTimeout kengine.Duration `json:"idle_timeout,omitempty"`

	// KeepAliveInterval is the interval at which TCP keepalive packets
	// are sent to keep the connection alive at the TCP layer when no other
	// data is being transmitted. The default is 15s.
	KeepAliveInterval kengine.Duration `json:"keepalive_interval,omitempty"`

	// MaxHeaderBytes is the maximum size to parse from a client's
	// HTTP request headers.
	MaxHeaderBytes int `json:"max_header_bytes,omitempty"`

	// Enable full-duplex communication for HTTP/1 requests.
	// Only has an effect if Kengine was built with Go 1.21 or later.
	//
	// For HTTP/1 requests, the Go HTTP server by default consumes any
	// unread portion of the request body before beginning to write the
	// response, preventing handlers from concurrently reading from the
	// request and writing the response. Enabling this option disables
	// this behavior and permits handlers to continue to read from the
	// request while concurrently writing the response.
	//
	// For HTTP/2 requests, the Go HTTP server always permits concurrent
	// reads and responses, so this option has no effect.
	//
	// Test thoroughly with your HTTP clients, as some older clients may
	// not support full-duplex HTTP/1 which can cause them to deadlock.
	// See https://github.com/golang/go/issues/57786 for more info.
	//
	// This is an EXPERIMENTAL feature. Subject to change or removal.
	EnableFullDuplex bool `json:"enable_full_duplex,omitempty"`

	// Routes describes how this server will handle requests.
	// Routes are executed sequentially. First a route's matchers
	// are evaluated, then its grouping. If it matches and has
	// not been mutually-excluded by its grouping, then its
	// handlers are executed sequentially. The sequence of invoked
	// handlers comprises a compiled middleware chain that flows
	// from each matching route and its handlers to the next.
	//
	// By default, all unrouted requests receive a 200 OK response
	// to indicate the server is working.
	Routes []Route `json:"routes,omitempty"`

	// Errors is how this server will handle errors returned from any
	// of the handlers in the primary routes. If the primary handler
	// chain returns an error, the error along with its recommended
	// status code are bubbled back up to the HTTP server which
	// executes a separate error route, specified using this property.
	// The error routes work exactly like the normal routes.
	Errors *HTTPErrorConfig `json:"errors,omitempty"`

	// NamedRoutes describes a mapping of reusable routes that can be
	// invoked by their name. This can be used to optimize memory usage
	// when the same route is needed for many subroutes, by having
	// the handlers and matchers be only provisioned once, but used from
	// many places. These routes are not executed unless they are invoked
	// from another route.
	//
	// EXPERIMENTAL: Subject to change or removal.
	NamedRoutes map[string]*Route `json:"named_routes,omitempty"`

	// How to handle TLS connections. At least one policy is
	// required to enable HTTPS on this server if automatic
	// HTTPS is disabled or does not apply.
	TLSConnPolicies kenginetls.ConnectionPolicies `json:"tls_connection_policies,omitempty"`

	// AutoHTTPS configures or disables automatic HTTPS within this server.
	// HTTPS is enabled automatically and by default when qualifying names
	// are present in a Host matcher and/or when the server is listening
	// only on the HTTPS port.
	AutoHTTPS *AutoHTTPSConfig `json:"automatic_https,omitempty"`

	// If true, will require that a request's Host header match
	// the value of the ServerName sent by the client's TLS
	// ClientHello; often a necessary safeguard when using TLS
	// client authentication.
	StrictSNIHost *bool `json:"strict_sni_host,omitempty"`

	// A module which provides a source of IP ranges, from which
	// requests should be trusted. By default, no proxies are
	// trusted.
	//
	// On its own, this configuration will not do anything,
	// but it can be used as a default set of ranges for
	// handlers or matchers in routes to pick up, instead
	// of needing to configure each of them. See the
	// `reverse_proxy` handler for example, which uses this
	// to trust sensitive incoming `X-Forwarded-*` headers.
	TrustedProxies *TrustedProxies `json:"trusted_proxies,omitempty"`

	// The headers from which the client IP address could be
	// read from. These will be considered in order, with the
	// first good value being used as the client IP.
	// By default, only `X-Forwarded-For` is considered.
	//
	// This depends on `trusted_proxies` being configured and
	// the request being validated as coming from a trusted
	// proxy, otherwise the client IP will be set to the direct
	// remote IP address.
	ClientIPHeaders []string `json:"client_ip_headers,omitempty"`

	// Enables access logging and configures how access logs are handled
	// in this server. To minimally enable access logs, simply set this
	// to a non-null, empty struct.
	Logs *ServerLogConfig `json:"logs,omitempty"`

	// Protocols specifies which HTTP protocols to enable.
	// Supported values are:
	//
	// - `h1` (HTTP/1.1)
	// - `h2` (HTTP/2)
	// - `h2c` (cleartext HTTP/2)
	// - `h3` (HTTP/3)
	//
	// If enabling `h2` or `h2c`, `h1` must also be enabled;
	// this is due to current limitations in the Go standard
	// library.
	//
	// HTTP/2 operates only over TLS (HTTPS). HTTP/3 opens
	// a UDP socket to serve QUIC connections.
	//
	// H2C operates over plain TCP if the client supports it;
	// however, because this is not implemented by the Go
	// standard library, other server options are not compatible
	// and will not be applied to H2C requests. Do not enable this
	// only to achieve maximum client compatibility. In practice,
	// very few clients implement H2C, and even fewer require it.
	// Enabling H2C can be useful for serving/proxying gRPC
	// if encryption is not possible or desired.
	//
	// We recommend for most users to simply let Kengine use the
	// default settings.
	//
	// Default: `[h1 h2 h3]`
	Protocols []string `json:"protocols,omitempty"`

	// If set, metrics observations will be enabled.
	// This setting is EXPERIMENTAL and subject to change.
	Metrics *Metrics `json:"metrics,omitempty"`
}

Server describes an HTTP server.

type ServerLogConfig

type ServerLogConfig struct {
	// The default logger name for all logs emitted by this server for
	// hostnames that are not in the LoggerNames (logger_names) map.
	DefaultLoggerName string `json:"default_logger_name,omitempty"`

	// LoggerNames maps request hostnames to a custom logger name.
	// For example, a mapping of "example.com" to "example" would
	// cause access logs from requests with a Host of example.com
	// to be emitted by a logger named "http.log.access.example".
	LoggerNames map[string]string `json:"logger_names,omitempty"`

	// By default, all requests to this server will be logged if
	// access logging is enabled. This field lists the request
	// hosts for which access logging should be disabled.
	SkipHosts []string `json:"skip_hosts,omitempty"`

	// If true, requests to any host not appearing in the
	// LoggerNames (logger_names) map will not be logged.
	SkipUnmappedHosts bool `json:"skip_unmapped_hosts,omitempty"`

	// If true, credentials that are otherwise omitted, will be logged.
	// The definition of credentials is defined by https://fetch.spec.whatwg.org/#credentials,
	// and this includes some request and response headers, i.e `Cookie`,
	// `Set-Cookie`, `Authorization`, and `Proxy-Authorization`.
	ShouldLogCredentials bool `json:"should_log_credentials,omitempty"`
}

ServerLogConfig describes a server's logging configuration. If enabled without customization, all requests to this server are logged to the default logger; logger destinations may be customized per-request-host.

type StaticError

type StaticError struct {
	// Handler is the name of this handler for the JSON config.
	// DO NOT USE this. This is a special value to represent this handler.
	// It will be overwritten when we are marshalled.
	Handler StaticErrorHandlerName `json:"handler"`

	// The error message. Optional. Default is no error message.
	Error string `json:"error,omitempty"`

	// The recommended HTTP status code. Can be either an integer or a
	// string if placeholders are needed. Optional. Default is 500.
	StatusCode WeakString `json:"status_code,omitempty"`
}

StaticError implements a simple handler that returns an error. This handler returns an error value, but does not write a response. This is useful when you want the server to act as if an error occurred; for example, to invoke your custom error handling logic.

Since this handler does not write a response, the error information is for use by the server to know how to handle the error.

func (StaticError) IAmAHandler

func (StaticError) IAmAHandler()

type StaticErrorHandlerName

type StaticErrorHandlerName string

func (StaticErrorHandlerName) MarshalJSON

func (StaticErrorHandlerName) MarshalJSON() ([]byte, error)

type StaticIPRange

type StaticIPRange struct {
	// Source is the name of this source for the JSON config.
	// DO NOT USE this. This is a special value to represent this source.
	// It will be overwritten when we are marshalled.
	Source StaticIPRangeSourceName `json:"source"`

	// A static list of IP ranges (supports CIDR notation).
	Ranges []string `json:"ranges,omitempty"`
}

StaticIPRange provides a static range of IP address prefixes (CIDRs).

type StaticIPRangeSourceName

type StaticIPRangeSourceName string

func (StaticIPRangeSourceName) MarshalJSON

func (StaticIPRangeSourceName) MarshalJSON() ([]byte, error)

type StaticResponse

type StaticResponse struct {
	// Handler is the name of this handler for the JSON config.
	// DO NOT USE this. This is a special value to represent this handler.
	// It will be overwritten when we are marshalled.
	Handler StaticResponseHandlerName `json:"handler"`

	// The HTTP status code to respond with. Can be an integer or,
	// if needing to use a placeholder, a string.
	//
	// If the status code is 103 (Early Hints), the response headers
	// will be written to the client immediately, the body will be
	// ignored, and the next handler will be invoked. This behavior
	// is EXPERIMENTAL while RFC 8297 is a draft, and may be changed
	// or removed.
	StatusCode WeakString `json:"status_code,omitempty"`

	// Header fields to set on the response; overwrites any existing
	// header fields of the same names after normalization.
	Headers http.Header `json:"headers,omitempty"`

	// The response body. If non-empty, the Content-Type header may
	// be added automatically if it is not explicitly configured nor
	// already set on the response; the default value is
	// "text/plain; charset=utf-8" unless the body is a valid JSON object
	// or array, in which case the value will be "application/json".
	// Other than those common special cases the Content-Type header
	// should be set explicitly if it is desired because MIME sniffing
	// is disabled for safety.
	Body string `json:"body,omitempty"`

	// If true, the server will close the client's connection
	// after writing the response.
	Close bool `json:"close,omitempty"`

	// Immediately and forcefully closes the connection without
	// writing a response. Interrupts any other HTTP streams on
	// the same connection.
	Abort bool `json:"abort,omitempty"`
}

StaticResponse implements a simple responder for static responses.

func (StaticResponse) IAmAHandler

func (StaticResponse) IAmAHandler()

type StaticResponseHandlerName

type StaticResponseHandlerName string

func (StaticResponseHandlerName) MarshalJSON

func (StaticResponseHandlerName) MarshalJSON() ([]byte, error)

type Subroute

type Subroute struct {
	// Handler is the name of this handler for the JSON config.
	// DO NOT USE this. This is a special value to represent this handler.
	// It will be overwritten when we are marshalled.
	Handler SubrouteHandlerName `json:"handler"`

	// The primary list of routes to compile and execute.
	Routes []Route `json:"routes,omitempty"`

	// If the primary routes return an error, error handling
	// can be promoted to this configuration instead.
	Errors *HTTPErrorConfig `json:"errors,omitempty"`
}

Subroute implements a handler that compiles and executes routes. This is useful for a batch of routes that all inherit the same matchers, or for multiple routes that should be treated as a single route.

You can also use subroutes to handle errors from its handlers. First the primary routes will be executed, and if they return an error, the errors routes will be executed; in that case, an error is only returned to the entry point at the server if there is an additional error returned from the errors routes.

func (Subroute) IAmAHandler

func (Subroute) IAmAHandler()

type SubrouteHandlerName

type SubrouteHandlerName string

func (SubrouteHandlerName) MarshalJSON

func (SubrouteHandlerName) MarshalJSON() ([]byte, error)

type TLSListenerWrapper

type TLSListenerWrapper struct {
	// Wrapper is the name of this wrapper for the JSON config.
	// DO NOT USE this. This is a special value to represent this wrapper.
	// It will be overwritten when we are marshalled.
	Wrapper TLSListenerWrapperName `json:"wrapper"`
}

TLSListenerWrapper . TODO: document

type TLSListenerWrapperName

type TLSListenerWrapperName string

func (TLSListenerWrapperName) MarshalJSON

func (TLSListenerWrapperName) MarshalJSON() ([]byte, error)

type TrustedProxies

type TrustedProxies struct {
	// Static .
	// TODO: document
	// ref; https://khulnasoft.com/docs/json/apps/http/servers/trusted_proxies/static/
	Static *StaticIPRange `json:"static,omitempty"`
}

TrustedProxies . TODO: document ref; https://khulnasoft.com/docs/json/apps/http/servers/trusted_proxies/

type VarsMiddleware

type VarsMiddleware map[string]any

VarsMiddleware is an HTTP middleware which sets variables to have values that can be used in the HTTP request handler chain. The primary way to access variables is with placeholders, which have the form: `{http.vars.variable_name}`, or with the `vars` and `vars_regexp` request matchers.

The key is the variable name, and the value is the value of the variable. Both the name and value may use or contain placeholders.

func (VarsMiddleware) IAmAHandler

func (VarsMiddleware) IAmAHandler()

func (VarsMiddleware) MarshalJSON

func (h VarsMiddleware) MarshalJSON() ([]byte, error)

type WeakString

type WeakString string

WeakString is a type that unmarshals any JSON value as a string literal, with the following exceptions:

1. actual string values are decoded as strings; and 2. null is decoded as empty string;

and provides methods for getting the value as various primitive types. However, using this type removes any type safety as far as deserializing JSON is concerned.

func (WeakString) MarshalJSON

func (ws WeakString) MarshalJSON() ([]byte, error)

MarshalJSON marshals was a boolean if true or false, a number if an integer, or a string otherwise.

func (*WeakString) UnmarshalJSON

func (ws *WeakString) UnmarshalJSON(b []byte) error

UnmarshalJSON satisfies json.Unmarshaler according to this type's documentation.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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