Documentation
¶
Overview ¶
Package httpengine is an HTTP/1.1 and HTTP/2 server for net/http handlers, with a second, allocation-free path for handlers written against its own Context.
HTTP/1.1 requests that arrive together (pipelined) are parsed and served in order from one read, and their responses leave in one write. On Linux and macOS, connections that only reach the FastHandler are served by epoll or kqueue event loops; a connection that needs blocking I/O (a streaming body, Flush, Hijack, HTTP/2, a net/http handler) moves to a goroutine of its own, the driver used everywhere else. HTTP/2 is served over TLS (ALPN "h2") and in cleartext (h2c, by prior knowledge or by Upgrade).
Index ¶
- Constants
- Variables
- func Listen(network, addr string) (net.Listener, error)
- func Prefork(ctx context.Context, n int) (worker bool, err error)
- type Context
- func (x *Context) AbortBody()
- func (x *Context) Body() ([]byte, error)
- func (x *Context) Context() context.Context
- func (x *Context) EndBody(body []byte)
- func (x *Context) Header(name string) []byte
- func (x *Context) Host() string
- func (x *Context) IsTLS() bool
- func (x *Context) Method() string
- func (x *Context) Path() string
- func (x *Context) PathBytes() []byte
- func (x *Context) QueryBytes(key string) []byte
- func (x *Context) RawQuery() string
- func (x *Context) RemoteAddr() string
- func (x *Context) Request() *http.Request
- func (x *Context) ResetResponse()
- func (x *Context) ResponseBody() []byte
- func (x *Context) ResponseHeader(key string) []byte
- func (x *Context) ResponseWriter() http.ResponseWriter
- func (x *Context) SetContentType(ct string)
- func (x *Context) SetHeader(key, value string)
- func (x *Context) SetHeaderBytes(key string, value []byte)
- func (x *Context) SetResponseBody(b []byte)
- func (x *Context) SetStatus(code int)
- func (x *Context) StartBody(status int, contentType string) []byte
- func (x *Context) Started() bool
- func (x *Context) Trailer(name string) string
- func (x *Context) Trailers() http.Header
- func (x *Context) VisitHeaders(fn func(name, value []byte))
- func (x *Context) Write(b []byte) (int, error)
- func (x *Context) WriteBytes(b []byte)
- func (x *Context) WriteJSON(v any) error
- func (x *Context) WriteString(s string)
- type FastHandler
- type FastHandlerFunc
- type InlineHandler
- type Option
- func WithBaseContext(ctx context.Context) Option
- func WithFastHandler(h FastHandler) Option
- func WithH2C(on bool) Option
- func WithHTTP2(on bool) Option
- func WithHandler(h http.Handler) Option
- func WithIdleTimeout(d time.Duration) Option
- func WithInlineDispatch(on bool) Option
- func WithMaxBodyBytes(n int64) Option
- func WithMaxConcurrentStreams(n uint32) Option
- func WithMaxHeaderBytes(n int) Option
- func WithReactor(on bool) Option
- func WithReadHeaderTimeout(d time.Duration) Option
- func WithReadTimeout(d time.Duration) Option
- func WithServerName(name string) Option
- func WithTLSConfig(cfg *tls.Config) Option
- func WithWorkers(n int) Option
- func WithWriteTimeout(d time.Duration) Option
- type Server
Constants ¶
const PreforkWorkerEnv = "HTTPENGINE_PREFORK_WORKER"
PreforkWorkerEnv is set, to the worker's number from 1, in the environment of each worker process Prefork starts.
Variables ¶
var ErrServerClosed = http.ErrServerClosed
ErrServerClosed is returned by Serve after Shutdown or Close; it is http.ErrServerClosed, so code written for net/http matches it.
Functions ¶
func Listen ¶
Listen listens like net.Listen, with SO_REUSEADDR and SO_REUSEPORT set so that, on Linux, Serve can open one socket per event loop on the same address and let the kernel spread connections over them.
func Prefork ¶ added in v0.3.0
Prefork serves with n processes instead of one. Call it first in main, before opening listeners, pools, or anything else a process owns.
In the starting process it runs n copies of the program, with its arguments and environment plus GOMAXPROCS=1 and PreforkWorkerEnv, and returns worker false once they have all exited: after ctx is done, when it sends each one SIGTERM (and SIGKILL 30s later), or after one exits on its own, when it stops the rest and returns an error naming it. In a worker it returns worker true at once; the program then serves as usual, listening with Listen on a fixed port, which SO_REUSEPORT lets every worker share. A worker gets SIGTERM if the starting process dies.
The kernel spreads connections over the workers only on Linux. Elsewhere, or with n < 2, Prefork returns worker true at once and the program serves in this one process. Workers share no memory: each has its own in-process caches, sessions, and queues.
Types ¶
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context is one HTTP/1.x request and its response. The server reuses it for the next request on the connection, so a handler must not keep it, or any slice it returned, after ServeFast returns. Strings it returns (Method, Path, RawQuery) are copies and may be kept.
The response is buffered and sent with a Content-Length once the handler returns, together with the other responses of a pipelined batch.
func (*Context) AbortBody ¶ added in v0.3.0
func (x *Context) AbortBody()
AbortBody gives up the response StartBody began and leaves the response as it was before.
func (*Context) Body ¶
Body returns the whole request body, reading the rest of it from the connection when it is not yet buffered. A body over the server's MaxBodyBytes is an error. The slice may alias the read buffer: it is valid until ServeFast returns.
func (*Context) Context ¶
Context returns the request context. It is canceled when the handler returns, and earlier if the client goes away while something waits on it.
func (*Context) EndBody ¶ added in v0.3.0
EndBody finishes the response StartBody began, with body: the buffer StartBody returned, with the body appended.
func (*Context) Header ¶
Header returns the first value of the request header name, matched without regard to case, or nil. It aliases the read buffer.
func (*Context) Host ¶ added in v0.3.0
Host returns the request host as the Host header sent it, or the host of an absolute-form request target when there is no Host header, as the net/http adapter sets Request.Host. It is "" for an HTTP/1.0 request with neither.
func (*Context) PathBytes ¶
PathBytes is the raw request path, before percent-decoding. It aliases the read buffer.
func (*Context) QueryBytes ¶
QueryBytes returns the raw value of the first query parameter key, or nil. It aliases the read buffer and is not percent-decoded.
func (*Context) RemoteAddr ¶
RemoteAddr returns the client's address.
func (*Context) ResetResponse ¶
func (x *Context) ResetResponse()
ResetResponse discards the status, headers, and body set so far. It does nothing once Started.
func (*Context) ResponseBody ¶
ResponseBody returns the response body written so far, for a handler that builds it in place.
func (*Context) ResponseHeader ¶ added in v0.3.0
ResponseHeader returns the value of the response header key set so far, matched without regard to case, or nil. It aliases the Context's storage: it is valid until ServeFast returns and must not be modified.
func (*Context) ResponseWriter ¶
func (x *Context) ResponseWriter() http.ResponseWriter
ResponseWriter returns an http.ResponseWriter for this response, sharing its status, headers, and body. Use it to hand the request to net/http code; it supports http.Flusher and http.Hijacker.
func (*Context) SetContentType ¶
SetContentType sets the Content-Type of the response.
func (*Context) SetHeaderBytes ¶ added in v0.3.0
SetHeaderBytes is SetHeader with the value in bytes, which it copies into storage the Context reuses for later requests, so a value built in a scratch buffer costs no allocation.
func (*Context) SetResponseBody ¶
SetResponseBody replaces the response body with b, which the Context keeps and reuses for later requests.
func (*Context) StartBody ¶ added in v0.3.0
StartBody begins a response whose body the caller appends in place: it sets the status and Content-Type and returns dst, the buffer to append the body to. When the response has no body yet, dst is the connection's output itself, after the response head, so the body is never copied. Pass dst with the body appended to EndBody, or call AbortBody to leave the response as it was, before calling any other method of x; later changes to the response still apply.
func (*Context) Started ¶
Started reports whether part of the response has gone to the connection, through Flush or Hijack on the ResponseWriter. Until then the handler can still replace all of it.
func (*Context) Trailer ¶
Trailer returns the first value of the request trailer field name, matched without regard to case, or "". Trailers arrive after the body, so it is "" until the body has been read to the end.
func (*Context) Trailers ¶
Trailers returns the request trailer fields, canonicalized as net/http does, once the body has been read to the end; nil if there are none.
func (*Context) VisitHeaders ¶
VisitHeaders calls fn for each request header field in order.
func (*Context) WriteBytes ¶
WriteBytes appends b to the response body.
func (*Context) WriteJSON ¶
WriteJSON encodes v as JSON into the response body and sets the Content-Type to application/json unless one is set.
func (*Context) WriteString ¶
WriteString appends s to the response body.
type FastHandler ¶
FastHandler serves a request on its Context, without net/http types. It returns false, having read and written nothing, to pass the request to the server's http.Handler instead.
type FastHandlerFunc ¶
FastHandlerFunc adapts a function to FastHandler.
func (FastHandlerFunc) ServeFast ¶
func (f FastHandlerFunc) ServeFast(x *Context) bool
ServeFast calls f(x).
type InlineHandler ¶ added in v0.3.0
type InlineHandler interface {
FastHandler
// InlineFast reports whether ServeFast serves x without waiting on
// I/O, locks, or anything else that can block. It must not read or
// write the response.
InlineFast(x *Context) bool
}
InlineHandler is a FastHandler that knows which requests it serves without blocking. On an event loop, unless WithInlineDispatch is on, the loop asks InlineFast about each request it parses and serves the ones it accepts itself; the first one it refuses, and the rest of the batch after it, go to another goroutine as they would without InlineFast.
type Option ¶
type Option func(*config)
Option configures a Server.
func WithBaseContext ¶
WithBaseContext sets the context whose values every request context carries. Its cancellation is not propagated.
func WithFastHandler ¶
func WithFastHandler(h FastHandler) Option
WithFastHandler sets the handler that sees each HTTP/1.x request first.
func WithH2C ¶
WithH2C turns cleartext HTTP/2 on or off: prior knowledge and the HTTP/1.1 Upgrade. Default on, when HTTP/2 is on.
func WithHandler ¶
WithHandler sets the net/http handler. Default: http.NotFoundHandler.
func WithIdleTimeout ¶
WithIdleTimeout bounds the wait for the next request on a kept-alive connection. Default: the read timeout.
func WithInlineDispatch ¶
WithInlineDispatch runs the FastHandler on the event loop itself instead of on a goroutine per busy connection. It is faster for handlers that never block, and stalls every connection of the loop while one does: use it only when no FastHandler route waits on I/O. An InlineHandler gets the same speed for the requests it names, with blocking ones kept off the loop.
func WithMaxBodyBytes ¶
WithMaxBodyBytes caps a request body; a larger declared body gets 413 before any handler runs, a larger chunked one fails the body read. Default 0: no limit, as net/http.
func WithMaxConcurrentStreams ¶
WithMaxConcurrentStreams sets SETTINGS_MAX_CONCURRENT_STREAMS. Default 250.
func WithMaxHeaderBytes ¶
WithMaxHeaderBytes caps the request line plus header fields. Default 1 MiB, as net/http.
func WithReactor ¶
WithReactor turns the epoll/kqueue event loops on or off. They are used only on Linux and macOS, for cleartext listeners, with a FastHandler. Default on.
func WithReadHeaderTimeout ¶
WithReadHeaderTimeout bounds reading one request head, counted from its first byte. Default: the read timeout.
func WithReadTimeout ¶
WithReadTimeout bounds reading one request, head and body. Default none.
func WithServerName ¶
WithServerName sets the Server header of every response that does not set its own. Default: none.
func WithTLSConfig ¶
WithTLSConfig serves TLS with cfg. "h2" and "http/1.1" are added to its NextProtos for ALPN unless HTTP/2 is off.
func WithWorkers ¶
WithWorkers sets the number of event loops. Default GOMAXPROCS.
func WithWriteTimeout ¶
WithWriteTimeout bounds each write of a response. Default none.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server serves HTTP/1.1 and HTTP/2.
func (*Server) ListenAndServe ¶
ListenAndServe listens on the TCP address addr with Listen and serves.
func (*Server) RegisterOnShutdown ¶
func (s *Server) RegisterOnShutdown(f func())
RegisterOnShutdown registers f to run, in its own goroutine, when Shutdown starts: the place to tell hijacked and streaming connections to wind down.