httpengine

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0, MIT Imports: 29 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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

View Source
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

func Listen(network, addr string) (net.Listener, error)

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

func Prefork(ctx context.Context, n int) (worker bool, err error)

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

func (x *Context) Body() ([]byte, error)

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

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

func (x *Context) EndBody(body []byte)

EndBody finishes the response StartBody began, with body: the buffer StartBody returned, with the body appended.

func (*Context) Header

func (x *Context) Header(name string) []byte

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

func (x *Context) Host() string

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) IsTLS

func (x *Context) IsTLS() bool

IsTLS reports whether the connection is TLS.

func (*Context) Method

func (x *Context) Method() string

Method returns the request method.

func (*Context) Path

func (x *Context) Path() string

Path returns the request path, percent-decoded as URL.Path is.

func (*Context) PathBytes

func (x *Context) PathBytes() []byte

PathBytes is the raw request path, before percent-decoding. It aliases the read buffer.

func (*Context) QueryBytes

func (x *Context) QueryBytes(key string) []byte

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) RawQuery

func (x *Context) RawQuery() string

RawQuery returns the query string, without the '?', still encoded.

func (*Context) RemoteAddr

func (x *Context) RemoteAddr() string

RemoteAddr returns the client's address.

func (*Context) Request

func (x *Context) Request() *http.Request

Request returns the request as an *http.Request, built on first use.

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

func (x *Context) ResponseBody() []byte

ResponseBody returns the response body written so far, for a handler that builds it in place.

func (*Context) ResponseHeader added in v0.3.0

func (x *Context) ResponseHeader(key string) []byte

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

func (x *Context) SetContentType(ct string)

SetContentType sets the Content-Type of the response.

func (*Context) SetHeader

func (x *Context) SetHeader(key, value string)

SetHeader sets a response header, replacing any value it had.

func (*Context) SetHeaderBytes added in v0.3.0

func (x *Context) SetHeaderBytes(key string, value []byte)

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

func (x *Context) SetResponseBody(b []byte)

SetResponseBody replaces the response body with b, which the Context keeps and reuses for later requests.

func (*Context) SetStatus

func (x *Context) SetStatus(code int)

SetStatus sets the response status. Default 200.

func (*Context) StartBody added in v0.3.0

func (x *Context) StartBody(status int, contentType string) []byte

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

func (x *Context) Started() bool

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

func (x *Context) Trailer(name string) string

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

func (x *Context) Trailers() http.Header

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

func (x *Context) VisitHeaders(fn func(name, value []byte))

VisitHeaders calls fn for each request header field in order.

func (*Context) Write

func (x *Context) Write(b []byte) (int, error)

Write appends b to the response body.

func (*Context) WriteBytes

func (x *Context) WriteBytes(b []byte)

WriteBytes appends b to the response body.

func (*Context) WriteJSON

func (x *Context) WriteJSON(v any) error

WriteJSON encodes v as JSON into the response body and sets the Content-Type to application/json unless one is set.

func (*Context) WriteString

func (x *Context) WriteString(s string)

WriteString appends s to the response body.

type FastHandler

type FastHandler interface {
	ServeFast(x *Context) bool
}

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

type FastHandlerFunc func(x *Context) bool

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

func WithBaseContext(ctx context.Context) Option

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

func WithH2C(on bool) Option

WithH2C turns cleartext HTTP/2 on or off: prior knowledge and the HTTP/1.1 Upgrade. Default on, when HTTP/2 is on.

func WithHTTP2

func WithHTTP2(on bool) Option

WithHTTP2 turns HTTP/2 (TLS ALPN and h2c) on or off. Default on.

func WithHandler

func WithHandler(h http.Handler) Option

WithHandler sets the net/http handler. Default: http.NotFoundHandler.

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) Option

WithIdleTimeout bounds the wait for the next request on a kept-alive connection. Default: the read timeout.

func WithInlineDispatch

func WithInlineDispatch(on bool) Option

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

func WithMaxBodyBytes(n int64) Option

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

func WithMaxConcurrentStreams(n uint32) Option

WithMaxConcurrentStreams sets SETTINGS_MAX_CONCURRENT_STREAMS. Default 250.

func WithMaxHeaderBytes

func WithMaxHeaderBytes(n int) Option

WithMaxHeaderBytes caps the request line plus header fields. Default 1 MiB, as net/http.

func WithReactor

func WithReactor(on bool) Option

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

func WithReadHeaderTimeout(d time.Duration) Option

WithReadHeaderTimeout bounds reading one request head, counted from its first byte. Default: the read timeout.

func WithReadTimeout

func WithReadTimeout(d time.Duration) Option

WithReadTimeout bounds reading one request, head and body. Default none.

func WithServerName

func WithServerName(name string) Option

WithServerName sets the Server header of every response that does not set its own. Default: none.

func WithTLSConfig

func WithTLSConfig(cfg *tls.Config) Option

WithTLSConfig serves TLS with cfg. "h2" and "http/1.1" are added to its NextProtos for ALPN unless HTTP/2 is off.

func WithWorkers

func WithWorkers(n int) Option

WithWorkers sets the number of event loops. Default GOMAXPROCS.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) Option

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 New

func New(opts ...Option) *Server

New returns a Server configured by opts.

func (*Server) Close

func (s *Server) Close() error

Close closes the listeners and every tracked connection at once.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(addr string) error

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.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve accepts connections on ln until Shutdown or Close, and closes ln. It returns ErrServerClosed after either.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown stops accepting, closes idle connections, tells HTTP/2 clients to go away, and waits for active requests to finish, or for ctx to be done, whose error it then returns. Hijacked connections are not tracked.

Jump to

Keyboard shortcuts

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