Help us shape the future of Go! Take the 2026 Go Developer Survey

httputil

package
v1.3.104 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: AGPL-3.0 Imports: 24 Imported by: 0

Documentation

Overview

Package httputil pkg/httputil/compress.go c0-com-util

Package httputil pkg/httputil/dmsghttp.go c0-com-http

Package httputil pkg/httputil/error.go c0-com-http

Package httputil pkg/httputil/health.go c0-com-http

Package httputil pkg/httputil/httputil.go c0-com-http

Package httputil pkg/httputil/json.go c0-com-http

Package httputil pkg/httputil/limit.go c0-com-util

Package httputil pkg/httputil/log.go c0-com-http

Package httputil pkg/httputil/middleware.go

Package httputil pkg/httputil/recover.go

Package httputil pkg/httputil/router.go

Index

Constants

View Source
const CompressMinBytes = 1024

CompressMinBytes is the default body size below which CompressMin leaves a response uncompressed. The deployment services answer most requests with a few hundred bytes (one entry, one binding, one health line); gzipping those costs a flate writer (~800 KB of state, pooled) and CPU for no wire saving — flate was 15% of dmsg-discovery's CPU and the pooled writers 110 MB of the address resolver's heap (2026-09-10).

View Source
const LoggerKey ctxKeyLogger = -1

LoggerKey defines logger HTTP context key.

Variables

View Source
var RequestLogSlow = 2 * time.Second

RequestLogSlow is the latency above which a request that otherwise succeeded is still logged at Info. A var, not a const, so tests can lower it.

Functions

func BodyTooLarge added in v1.3.100

func BodyTooLarge(err error) bool

BodyTooLarge reports whether err came from a body read that passed the LimitBody cap.

func BoolFromQuery

func BoolFromQuery(r *http.Request, key string, defaultVal bool) (bool, error)

BoolFromQuery obtains a boolean from a query entry.

func CompressMin

func CompressMin(minBytes, level int) func(http.Handler) http.Handler

CompressMin gzips responses larger than minBytes for clients that accept gzip, when the content type is text, JSON, JavaScript, XML or SVG. Smaller responses, other types, flushes before the threshold, and hijacked connections pass through untouched. level is a compress/gzip level.

func ErrorFromResp

func ErrorFromResp(resp *http.Response) error

ErrorFromResp creates an HTTPError from a given server response.

func GetLogger

func GetLogger(r *http.Request) logrus.FieldLogger

GetLogger returns the logger carried by the HTTP request context, or the package logger when the context has none.

The miss is the common case, not an edge case: SetLoggerMiddleware only puts a logger in the context when a request ID is present. This used to return logging.NewMasterLogger(), which built a whole logrus.Logger, TextFormatter and hook map per call, and whose entries then bypassed the process hooks and configured level because it was its own master. The package logger is created once and routes through the master logger, so hooks and level apply.

func GetReqID added in v1.3.101

func GetReqID(ctx context.Context) string

GetReqID returns the request ID that RequestID stored in ctx, or "".

func KeyByRemoteAddr added in v1.3.101

func KeyByRemoteAddr(r *http.Request) string

KeyByRemoteAddr keys a rate limit by the peer IP, an IPv6 peer by its /64.

func LimitBody added in v1.3.100

func LimitBody(n int64) func(http.Handler) http.Handler

LimitBody caps request bodies at n bytes. A declared Content-Length over n is answered 413 at once, and any other body fails its read past n.

func LogEntrySetField

func LogEntrySetField(r *http.Request, key string, value interface{})

LogEntrySetField adds new key-value pair to current (request scoped) log entry. This pair will be printed along with all other pairs when the request is served. This requires log middleware from this package to be installed in the chain

func NewLogMiddleware

func NewLogMiddleware(logger logrus.FieldLogger) func(http.Handler) http.Handler

NewLogMiddleware creates a new instance of logging middleware. This will allow adding log fields in the handler and any further middleware. At the end of request, this log entry will be printed at Info level via passed logger

func ReadJSON

func ReadJSON(r *http.Request, v interface{}) error

ReadJSON reads the request body to a json object.

func RealIP added in v1.3.101

func RealIP(next http.Handler) http.Handler

RealIP sets r.RemoteAddr from True-Client-IP, X-Real-IP or the first X-Forwarded-For address, when one holds a valid IP.

func Recoverer added in v1.3.101

func Recoverer(next http.Handler) http.Handler

Recoverer turns a handler panic into a 500 and logs it with the stack, so one bad request does not take the server down. http.ErrAbortHandler passes through.

func RequestID added in v1.3.101

func RequestID(next http.Handler) http.Handler

RequestID gives each request an ID, the X-Request-Id header when the client sent one. GetReqID reads it back.

func SetLoggerMiddleware

func SetLoggerMiddleware(log logrus.FieldLogger) func(next http.Handler) http.Handler

SetLoggerMiddleware sets logger to context of HTTP requests.

func TrackRoutePattern added in v1.3.101

func TrackRoutePattern(r *http.Request) (*http.Request, *string)

TrackRoutePattern returns a request whose Router route, once served, is readable from the returned pointer, such as "/api/services/{addr}".

func WithReqID added in v1.3.101

func WithReqID(ctx context.Context, id string) context.Context

WithReqID returns ctx carrying a request ID, for tests.

func WriteJSON

func WriteJSON(w http.ResponseWriter, r *http.Request, code int, v interface{})

WriteJSON writes a json object on a http.ResponseWriter with the given code. A value that cannot be encoded answers 500. Write errors are only logged.

Types

type CORSOptions added in v1.3.101

type CORSOptions struct {
	AllowedOrigins []string // "*" allows any
	AllowedMethods []string
	AllowedHeaders []string
	ExposedHeaders []string
	MaxAge         int // seconds a preflight may be cached
}

CORSOptions configures CORS.

type DMSGHTTPConf

type DMSGHTTPConf struct {
	DMSGServers        []DMSGServersConf `json:"dmsg_servers"`
	DMSGDiscovery      string            `json:"dmsg_discovery"`
	TranspordDiscovery string            `json:"transport_discovery"`
	AddressResolver    string            `json:"address_resolver"`
	RouteFinder        string            `json:"route_finder"`
	ServiceDiscovery   string            `json:"service_discovery"`
}

DMSGHTTPConf is struct of /dmsghttp endpoint of config bootstrap

type DMSGServersConf

type DMSGServersConf struct {
	Static string `json:"static"`
	Server struct {
		Address string `json:"address"`
	} `json:"server"`
}

DMSGServersConf is struct of dmsg servers list on /dmsghttp endpoint

type DmsgServerHealth added in v1.3.100

type DmsgServerHealth struct {
	ClientSessions int    `json:"client_sessions"`
	PeerSessions   int    `json:"peer_sessions"`
	ActiveStreams  int64  `json:"active_streams"`
	StreamsRelayed uint64 `json:"streams_relayed"`
	BytesUp        uint64 `json:"bytes_up"`
	BytesDown      uint64 `json:"bytes_down"`
}

DmsgServerHealth is a dmsg server's load: its connections, and the streams it relays and the bytes they carried since it started.

func DmsgServerHealthOf added in v1.3.100

func DmsgServerHealthOf(clients, peers int, active int64, streams, up, down uint64) *DmsgServerHealth

DmsgServerHealthOf converts a server's Stats for /health.

type Error

type Error struct {
	Error string `json:"error"`
}

Error is the object returned to the client when there's an error.

type HTTPError

type HTTPError struct {
	Status int
	Body   string
}

HTTPError represents an http error associated with a server response.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error returns the error message.

func (*HTTPError) Temporary

func (e *HTTPError) Temporary() bool

Temporary implements net.Error

func (*HTTPError) Timeout

func (e *HTTPError) Timeout() bool

Timeout implements net.Error

type HealthCheckResponse

type HealthCheckResponse struct {
	ServiceName       string          `json:"service_name,omitempty"`
	BuildInfo         *buildinfo.Info `json:"build_info,omitempty"`
	StartedAt         time.Time       `json:"started_at"`
	PublicKey         string          `json:"public_key,omitempty"`
	DmsgAddr          string          `json:"dmsg_address,omitempty"`
	DmsgDiscovery     string          `json:"dmsg_discovery,omitempty"`
	DmsgServers       []string        `json:"dmsg_servers,omitempty"`
	PeerServers       []string        `json:"peer_servers,omitempty"`
	PublicAutoconnect bool            `json:"public_autoconnect,omitempty"`
	StcprCount        int             `json:"stcpr_count,omitempty"`
	SudphCount        int             `json:"sudph_count,omitempty"`
	// TransportCounts is a count of live transports keyed by their actual
	// network type (stcpr, sudph, stcp, dmsg, squicr, swsr, swtr, webrtc, …).
	// The key set is derived from the transports present, so every current and
	// future transport type is represented — not just stcpr/sudph. The legacy
	// StcprCount/SudphCount fields remain for backward compatibility.
	TransportCounts map[string]int `json:"transport_counts,omitempty"`
	NetworkTypes    []string       `json:"network_types,omitempty"`
	DHTBootstrap    bool           `json:"dht_bootstrap,omitempty"`
	// UDPAddr is an address resolver's public SUDPH address: visors that
	// reach it over dmsg register SUDPH with it. Empty when not configured.
	UDPAddr string `json:"udp_address,omitempty"`
	// DmsgSessions are the visor's own sessions with dmsg servers.
	DmsgSessions int `json:"dmsg_sessions,omitempty"`
	// DmsgServer is what the dmsg server this process runs is carrying.
	DmsgServer *DmsgServerHealth `json:"dmsg_server,omitempty"`
}

HealthCheckResponse is struct of /health endpoint

type Middleware added in v1.3.101

type Middleware = func(http.Handler) http.Handler

Middleware wraps a handler.

func CORS added in v1.3.101

func CORS(o CORSOptions) Middleware

CORS answers preflight requests and adds CORS headers to the others.

func RateLimit added in v1.3.101

func RateLimit(limit int, window time.Duration, key func(*http.Request) string) Middleware

RateLimit allows limit requests per window for each key and answers 429 past that. It estimates a sliding window from the current and previous fixed windows, as go-chi/httprate does.

func Timeout added in v1.3.101

func Timeout(d time.Duration) Middleware

Timeout cancels the request context after d and answers 504 when the handler returns on that deadline. Unlike http.TimeoutHandler it does not buffer the response, so streaming and hijacking still work.

type Router added in v1.3.101

type Router struct {
	// contains filtered or unexported fields
}

Router is an http.ServeMux with middleware groups and path prefixes. Paths use ServeMux wildcards ({pk}, {rest...}). A path ending in "/" matches only itself, and Get("/") inside Route("/api") answers both "/api" and "/api/". Route owns its prefix: an unmatched path below it gets 404 or 405 there and never reaches a broader route such as "/{rest...}".

func NewRouter added in v1.3.101

func NewRouter() *Router

NewRouter returns an empty Router.

func (*Router) Delete added in v1.3.101

func (rt *Router) Delete(path string, h http.HandlerFunc)

Delete registers h for DELETE on path.

func (*Router) Get added in v1.3.101

func (rt *Router) Get(path string, h http.HandlerFunc)

Get registers h for GET (and HEAD) on path.

func (*Router) Group added in v1.3.101

func (rt *Router) Group(fn func(r *Router))

Group registers routes that share middleware added inside fn.

func (*Router) Handle added in v1.3.101

func (rt *Router) Handle(path string, h http.Handler)

Handle registers h for path and any method.

func (*Router) HandleFunc added in v1.3.101

func (rt *Router) HandleFunc(path string, h http.HandlerFunc)

HandleFunc registers h for path and any method.

func (*Router) Mount added in v1.3.101

func (rt *Router) Mount(prefix string, h http.Handler)

Mount serves prefix and everything below it with h. h sees the full path.

func (*Router) Patch added in v1.3.101

func (rt *Router) Patch(path string, h http.HandlerFunc)

Patch registers h for PATCH on path.

func (*Router) Post added in v1.3.101

func (rt *Router) Post(path string, h http.HandlerFunc)

Post registers h for POST on path.

func (*Router) Put added in v1.3.101

func (rt *Router) Put(path string, h http.HandlerFunc)

Put registers h for PUT on path.

func (*Router) Route added in v1.3.101

func (rt *Router) Route(prefix string, fn func(r *Router))

Route registers routes under prefix.

func (*Router) ServeHTTP added in v1.3.101

func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP runs the root middleware and then the matching route.

func (*Router) Use added in v1.3.101

func (rt *Router) Use(mws ...Middleware)

Use adds middleware. On the root it runs for every request, before routing and for unmatched paths too. In a Group or Route it wraps that group's routes.

func (*Router) With added in v1.3.101

func (rt *Router) With(mws ...Middleware) *Router

With returns a Router whose routes also run mws.

type StatusWriter added in v1.3.101

type StatusWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

StatusWriter records the status code and body size a handler wrote. It passes Flush and Hijack through to the writer it wraps.

func (*StatusWriter) BytesWritten added in v1.3.101

func (s *StatusWriter) BytesWritten() int

BytesWritten is the body size sent.

func (*StatusWriter) Flush added in v1.3.101

func (s *StatusWriter) Flush()

Flush sends buffered data to the client.

func (*StatusWriter) Hijack added in v1.3.101

func (s *StatusWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack lets the handler take over the connection.

func (*StatusWriter) Status added in v1.3.101

func (s *StatusWriter) Status() int

Status is the code sent, 200 when the handler wrote nothing.

func (*StatusWriter) Unwrap added in v1.3.101

func (s *StatusWriter) Unwrap() http.ResponseWriter

Unwrap returns the wrapped writer, for http.ResponseController.

func (*StatusWriter) Write added in v1.3.101

func (s *StatusWriter) Write(p []byte) (int, error)

Write records that a body was sent, with an implicit 200.

func (*StatusWriter) WriteHeader added in v1.3.101

func (s *StatusWriter) WriteHeader(code int)

WriteHeader records code and sends it.

Jump to

Keyboard shortcuts

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