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
- Variables
- func BodyTooLarge(err error) bool
- func BoolFromQuery(r *http.Request, key string, defaultVal bool) (bool, error)
- func CompressMin(minBytes, level int) func(http.Handler) http.Handler
- func ErrorFromResp(resp *http.Response) error
- func GetLogger(r *http.Request) logrus.FieldLogger
- func GetReqID(ctx context.Context) string
- func KeyByRemoteAddr(r *http.Request) string
- func LimitBody(n int64) func(http.Handler) http.Handler
- func LogEntrySetField(r *http.Request, key string, value interface{})
- func NewLogMiddleware(logger logrus.FieldLogger) func(http.Handler) http.Handler
- func ReadJSON(r *http.Request, v interface{}) error
- func RealIP(next http.Handler) http.Handler
- func Recoverer(next http.Handler) http.Handler
- func RequestID(next http.Handler) http.Handler
- func SetLoggerMiddleware(log logrus.FieldLogger) func(next http.Handler) http.Handler
- func TrackRoutePattern(r *http.Request) (*http.Request, *string)
- func WithReqID(ctx context.Context, id string) context.Context
- func WriteJSON(w http.ResponseWriter, r *http.Request, code int, v interface{})
- type CORSOptions
- type DMSGHTTPConf
- type DMSGServersConf
- type DmsgServerHealth
- type Error
- type HTTPError
- type HealthCheckResponse
- type Middleware
- type Router
- func (rt *Router) Delete(path string, h http.HandlerFunc)
- func (rt *Router) Get(path string, h http.HandlerFunc)
- func (rt *Router) Group(fn func(r *Router))
- func (rt *Router) Handle(path string, h http.Handler)
- func (rt *Router) HandleFunc(path string, h http.HandlerFunc)
- func (rt *Router) Mount(prefix string, h http.Handler)
- func (rt *Router) Patch(path string, h http.HandlerFunc)
- func (rt *Router) Post(path string, h http.HandlerFunc)
- func (rt *Router) Put(path string, h http.HandlerFunc)
- func (rt *Router) Route(prefix string, fn func(r *Router))
- func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (rt *Router) Use(mws ...Middleware)
- func (rt *Router) With(mws ...Middleware) *Router
- type StatusWriter
- func (s *StatusWriter) BytesWritten() int
- func (s *StatusWriter) Flush()
- func (s *StatusWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (s *StatusWriter) Status() int
- func (s *StatusWriter) Unwrap() http.ResponseWriter
- func (s *StatusWriter) Write(p []byte) (int, error)
- func (s *StatusWriter) WriteHeader(code int)
Constants ¶
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).
const LoggerKey ctxKeyLogger = -1
LoggerKey defines logger HTTP context key.
Variables ¶
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
BodyTooLarge reports whether err came from a body read that passed the LimitBody cap.
func BoolFromQuery ¶
BoolFromQuery obtains a boolean from a query entry.
func CompressMin ¶
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 ¶
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
GetReqID returns the request ID that RequestID stored in ctx, or "".
func KeyByRemoteAddr ¶ added in v1.3.101
KeyByRemoteAddr keys a rate limit by the peer IP, an IPv6 peer by its /64.
func LimitBody ¶ added in v1.3.100
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 ¶
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 ¶
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 RealIP ¶ added in v1.3.101
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
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
RequestID gives each request an ID, the X-Request-Id header when the client sent one. GetReqID reads it back.
func SetLoggerMiddleware ¶
SetLoggerMiddleware sets logger to context of HTTP requests.
func TrackRoutePattern ¶ added in v1.3.101
TrackRoutePattern returns a request whose Router route, once served, is readable from the returned pointer, such as "/api/services/{addr}".
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 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
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
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 (*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
Group registers routes that share middleware added inside fn.
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
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) 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.