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

httputil

package
v1.3.97 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2026 License: AGPL-3.0 Imports: 19 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_native.go c0-com-http

Native builds use jsoniter.ConfigFastest for the package-wide `json` codec. It relies on github.com/modern-go/reflect2, whose unsafe reflection (reflect.mapassign / unsafe_New / typedmemmove …) TinyGo's runtime does not provide, so the TinyGo build uses the standard library instead — see json_tinygo.go. Only NewEncoder/NewDecoder are used here, so the wire format is identical either way.

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

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 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 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 SetLoggerMiddleware

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

SetLoggerMiddleware sets logger to context of HTTP requests.

func SplitRPCAddr

func SplitRPCAddr(rpcAddr string) (host string, port uint16, err error)

SplitRPCAddr returns host and port and whatever error results from parsing the rpc address interface

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. I/O errors (client disconnect, timeout) are logged but don't cause panics. Marshaling errors panic as they indicate a programming error.

Types

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"`
	UptimeTracker      string            `json:"uptime_tracker"`
	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 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"`
}

HealthCheckResponse is struct of /health endpoint

func GetServiceHealth

func GetServiceHealth(ctx context.Context, url string) (health *HealthCheckResponse, err error)

GetServiceHealth gets the response from the given service url

Jump to

Keyboard shortcuts

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