Documentation
¶
Overview ¶
Package http provides small HTTP wrappers and helpers around the standard library net/http package.
This package primarily re-exports common net/http types and constants behind go-service aliases and provides a few convenience helpers used by transport wiring, such as:
- NewClient, which applies a client timeout and wraps a RoundTripper with OpenTelemetry instrumentation when tracing or metrics are enabled,
- NewServer, which builds an http.Server using configured timeouts and protocol settings,
- NewTelemetryHandler, which wraps a handler with OpenTelemetry server instrumentation when tracing or metrics are enabled,
- Router, which registers handlers on a mux together with route policy used by transport middleware,
- Pattern and ParseServiceMethod, which help standardize route naming for telemetry.
Server construction reads timeout keys from options.Map (`read_timeout`, `write_timeout`, `idle_timeout`, `read_header_timeout`) and also supports `max_header_bytes` as an SI size string.
Index ¶
- Constants
- Variables
- func IgnoreRedirect(_ *Request, _ []*Request) error
- func IsCrossOriginRedirect(req *Request) bool
- func NewClient(rt http.RoundTripper, timeout time.Duration) *http.Client
- func ParseServiceMethod(req *http.Request) (string, string)
- func ParseTime(value string) (time.Time, error)
- func Pattern(name env.Name, pattern string) string
- func Protocols() *http.Protocols
- func SameOrigin(prev, next *url.URL) bool
- func SameOriginRedirect(req *Request, via []*Request) error
- func StatusText(code int) string
- func Transport(cfg *tls.Config) *http.Transport
- type ChainedHandler
- type ChainedHandlers
- type Client
- type ClosingRoundTripper
- type Handler
- type HandlerFunc
- type Header
- type MaxBytesError
- type NotFoundHandler
- type Request
- type Response
- type ResponseWriter
- type RoundTripper
- type RoutePolicy
- type Router
- type ServeMux
- type Server
Constants ¶
const DefaultMaxHeaderBytes = http.DefaultMaxHeaderBytes
DefaultMaxHeaderBytes is an alias of http.DefaultMaxHeaderBytes.
const MethodConnect = http.MethodConnect
MethodConnect is an alias of http.MethodConnect.
const MethodDelete = http.MethodDelete
MethodDelete is an alias of http.MethodDelete.
const MethodGet = http.MethodGet
MethodGet is an alias of http.MethodGet.
const MethodHead = http.MethodHead
MethodHead is an alias of http.MethodHead.
const MethodOptions = http.MethodOptions
MethodOptions is an alias of http.MethodOptions.
const MethodPatch = http.MethodPatch
MethodPatch is an alias of http.MethodPatch.
const MethodPost = http.MethodPost
MethodPost is an alias of http.MethodPost.
const MethodPut = http.MethodPut
MethodPut is an alias of http.MethodPut.
const MethodTrace = http.MethodTrace
MethodTrace is an alias of http.MethodTrace.
const StatusAccepted = http.StatusAccepted
StatusAccepted is an alias of http.StatusAccepted.
const StatusAlreadyReported = http.StatusAlreadyReported
StatusAlreadyReported is an alias of http.StatusAlreadyReported.
const StatusBadGateway = http.StatusBadGateway
StatusBadGateway is an alias of http.StatusBadGateway.
const StatusBadRequest = http.StatusBadRequest
StatusBadRequest is an alias of http.StatusBadRequest.
const StatusClientClosedRequest = 499
StatusClientClosedRequest is the non-standard HTTP status code 499 used when the client closes the request.
const StatusConflict = http.StatusConflict
StatusConflict is an alias of http.StatusConflict.
const StatusContinue = http.StatusContinue
StatusContinue is an alias of http.StatusContinue.
const StatusCreated = http.StatusCreated
StatusCreated is an alias of http.StatusCreated.
const StatusEarlyHints = http.StatusEarlyHints
StatusEarlyHints is an alias of http.StatusEarlyHints.
const StatusExpectationFailed = http.StatusExpectationFailed
StatusExpectationFailed is an alias of http.StatusExpectationFailed.
const StatusFailedDependency = http.StatusFailedDependency
StatusFailedDependency is an alias of http.StatusFailedDependency.
const StatusForbidden = http.StatusForbidden
StatusForbidden is an alias of http.StatusForbidden.
const StatusFound = http.StatusFound
StatusFound is an alias of http.StatusFound.
const StatusGatewayTimeout = http.StatusGatewayTimeout
StatusGatewayTimeout is an alias of http.StatusGatewayTimeout.
const StatusGone = http.StatusGone
StatusGone is an alias of http.StatusGone.
const StatusHTTPVersionNotSupported = http.StatusHTTPVersionNotSupported
StatusHTTPVersionNotSupported is an alias of http.StatusHTTPVersionNotSupported.
const StatusIMUsed = http.StatusIMUsed
StatusIMUsed is an alias of http.StatusIMUsed.
const StatusInsufficientStorage = http.StatusInsufficientStorage
StatusInsufficientStorage is an alias of http.StatusInsufficientStorage.
const StatusInternalServerError = http.StatusInternalServerError
StatusInternalServerError is an alias of http.StatusInternalServerError.
const StatusLengthRequired = http.StatusLengthRequired
StatusLengthRequired is an alias of http.StatusLengthRequired.
const StatusLocked = http.StatusLocked
StatusLocked is an alias of http.StatusLocked.
const StatusLoopDetected = http.StatusLoopDetected
StatusLoopDetected is an alias of http.StatusLoopDetected.
const StatusMethodNotAllowed = http.StatusMethodNotAllowed
StatusMethodNotAllowed is an alias of http.StatusMethodNotAllowed.
const StatusMisdirectedRequest = http.StatusMisdirectedRequest
StatusMisdirectedRequest is an alias of http.StatusMisdirectedRequest.
const StatusMovedPermanently = http.StatusMovedPermanently
StatusMovedPermanently is an alias of http.StatusMovedPermanently.
const StatusMultiStatus = http.StatusMultiStatus
StatusMultiStatus is an alias of http.StatusMultiStatus.
const StatusMultipleChoices = http.StatusMultipleChoices
StatusMultipleChoices is an alias of http.StatusMultipleChoices.
const StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired
StatusNetworkAuthenticationRequired is an alias of http.StatusNetworkAuthenticationRequired.
const StatusNoContent = http.StatusNoContent
StatusNoContent is an alias of http.StatusNoContent.
const StatusNonAuthoritativeInfo = http.StatusNonAuthoritativeInfo
StatusNonAuthoritativeInfo is an alias of http.StatusNonAuthoritativeInfo.
const StatusNotAcceptable = http.StatusNotAcceptable
StatusNotAcceptable is an alias of http.StatusNotAcceptable.
const StatusNotExtended = http.StatusNotExtended
StatusNotExtended is an alias of http.StatusNotExtended.
const StatusNotFound = http.StatusNotFound
StatusNotFound is an alias of http.StatusNotFound.
const StatusNotImplemented = http.StatusNotImplemented
StatusNotImplemented is an alias of http.StatusNotImplemented.
const StatusNotModified = http.StatusNotModified
StatusNotModified is an alias of http.StatusNotModified.
const StatusOK = http.StatusOK
StatusOK is an alias of http.StatusOK.
const StatusPartialContent = http.StatusPartialContent
StatusPartialContent is an alias of http.StatusPartialContent.
const StatusPaymentRequired = http.StatusPaymentRequired
StatusPaymentRequired is an alias of http.StatusPaymentRequired.
const StatusPermanentRedirect = http.StatusPermanentRedirect
StatusPermanentRedirect is an alias of http.StatusPermanentRedirect.
const StatusPreconditionFailed = http.StatusPreconditionFailed
StatusPreconditionFailed is an alias of http.StatusPreconditionFailed.
const StatusPreconditionRequired = http.StatusPreconditionRequired
StatusPreconditionRequired is an alias of http.StatusPreconditionRequired.
const StatusProcessing = http.StatusProcessing
StatusProcessing is an alias of http.StatusProcessing.
const StatusProxyAuthRequired = http.StatusProxyAuthRequired
StatusProxyAuthRequired is an alias of http.StatusProxyAuthRequired.
const StatusRequestEntityTooLarge = http.StatusRequestEntityTooLarge
StatusRequestEntityTooLarge is an alias of http.StatusRequestEntityTooLarge.
const StatusRequestHeaderFieldsTooLarge = http.StatusRequestHeaderFieldsTooLarge
StatusRequestHeaderFieldsTooLarge is an alias of http.StatusRequestHeaderFieldsTooLarge.
const StatusRequestTimeout = http.StatusRequestTimeout
StatusRequestTimeout is an alias of http.StatusRequestTimeout.
const StatusRequestURITooLong = http.StatusRequestURITooLong
StatusRequestURITooLong is an alias of http.StatusRequestURITooLong.
const StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable
StatusRequestedRangeNotSatisfiable is an alias of http.StatusRequestedRangeNotSatisfiable.
const StatusResetContent = http.StatusResetContent
StatusResetContent is an alias of http.StatusResetContent.
const StatusSeeOther = http.StatusSeeOther
StatusSeeOther is an alias of http.StatusSeeOther.
StatusServiceUnavailable is an alias of http.StatusServiceUnavailable.
const StatusSwitchingProtocols = http.StatusSwitchingProtocols
StatusSwitchingProtocols is an alias of http.StatusSwitchingProtocols.
const StatusTeapot = http.StatusTeapot
StatusTeapot is an alias of http.StatusTeapot.
const StatusTemporaryRedirect = http.StatusTemporaryRedirect
StatusTemporaryRedirect is an alias of http.StatusTemporaryRedirect.
const StatusTooEarly = http.StatusTooEarly
StatusTooEarly is an alias of http.StatusTooEarly.
const StatusTooManyRequests = http.StatusTooManyRequests
StatusTooManyRequests is an alias of http.StatusTooManyRequests.
StatusUnauthorized is an alias of http.StatusUnauthorized.
StatusUnavailableForLegalReasons is an alias of http.StatusUnavailableForLegalReasons.
const StatusUnprocessableEntity = http.StatusUnprocessableEntity
StatusUnprocessableEntity is an alias of http.StatusUnprocessableEntity.
const StatusUnsupportedMediaType = http.StatusUnsupportedMediaType
StatusUnsupportedMediaType is an alias of http.StatusUnsupportedMediaType.
const StatusUpgradeRequired = http.StatusUpgradeRequired
StatusUpgradeRequired is an alias of http.StatusUpgradeRequired.
const StatusUseProxy = http.StatusUseProxy
StatusUseProxy is an alias of http.StatusUseProxy.
const StatusVariantAlsoNegotiates = http.StatusVariantAlsoNegotiates
StatusVariantAlsoNegotiates is an alias of http.StatusVariantAlsoNegotiates.
const TimeFormat = http.TimeFormat
TimeFormat is the HTTP time format layout.
It is an alias of http.TimeFormat.
Variables ¶
var DefaultTransport = http.DefaultTransport
DefaultTransport is an alias for http.DefaultTransport.
var ErrServerClosed = http.ErrServerClosed
ErrServerClosed is an alias for http.ErrServerClosed.
var ErrUseLastResponse = http.ErrUseLastResponse
ErrUseLastResponse is an alias for http.ErrUseLastResponse.
var NoBody = http.NoBody
NoBody is an alias for http.NoBody.
Functions ¶
func IgnoreRedirect ¶ added in v2.442.0
IgnoreRedirect returns redirect responses without following them.
func IsCrossOriginRedirect ¶ added in v2.465.0
IsCrossOriginRedirect reports whether req is a redirected request whose previous request used a different origin.
func NewClient ¶ added in v2.205.0
NewClient constructs an HTTP client with a request timeout.
When tracing or metrics are enabled, the returned client wraps the provided RoundTripper with a telemetry transport. When tracing is enabled, it also installs an httptrace-based client trace derived from the request context.
The provided timeout is assigned to http.Client.Timeout (total time limit for requests, including connection time, redirects, and reading the response body).
func ParseServiceMethod ¶ added in v2.189.0
ParseServiceMethod derives a logical "service" and "method" name from an HTTP request.
This helper is intended for consistent telemetry naming. It attempts to derive names from the request path when it follows the conventional go-service route shape:
/<service>/<method>
If the request path matches that shape, ParseServiceMethod returns the extracted service/method pair.
Otherwise it falls back to:
- method: lower-cased HTTP method (e.g. "get", "post")
- service: a best-effort name derived from the path:
- "root" when the path is empty or "/"
- otherwise the path without the leading "/" (e.g. "/health" -> "health")
func ParseTime ¶ added in v2.584.0
ParseTime parses an HTTP time value.
This is a thin wrapper around http.ParseTime and does not change semantics.
func Pattern ¶ added in v2.61.0
Pattern constructs a route pattern of the form "/<name><pattern>".
This helper is used to namespace routes by service name so different services can share a router/mux without colliding, and so route names are consistent across telemetry, server registration, and tests.
Example:
Pattern(name, "/debug/pprof/") // -> "/my-service/debug/pprof/"
func Protocols ¶
Protocols constructs an http.Protocols value enabling the HTTP protocols supported by go-service.
The returned configuration enables:
- HTTP/1.1
- HTTP/2 (when negotiated, typically over TLS)
- h2c (unencrypted HTTP/2)
This helper is used by go-service HTTP server and transport construction to consistently enable the same protocol set across servers and clients.
func SameOrigin ¶ added in v2.458.0
SameOrigin reports whether prev and next use the same URL origin.
func SameOriginRedirect ¶ added in v2.441.0
SameOriginRedirect limits same-origin redirect chains to the standard Go limit of ten requests.
It is intended for clients that add credentials or signatures in RoundTripper middleware, where Go's default cross-origin sensitive-header stripping is not enough because middleware may mint fresh credentials for each redirected request.
func StatusText ¶ added in v2.21.0
StatusText returns the standard HTTP status text for the given status code.
This is a thin wrapper around net/http.StatusText.
func Transport ¶
Transport constructs a tuned *http.Transport with reasonable defaults and an optional TLS config.
This helper is intended for services and clients that want consistent HTTP transport behavior without having to re-specify common timeouts and connection pool limits.
Defaults applied:
- Proxy: http.ProxyFromEnvironment
- ForceAttemptHTTP2: true (enables HTTP/2 where supported by the server and TLS config)
- Dialer: 1m connect timeout, 30s TCP keepalive
- Connection pool limits: 100 max total idle, 100 max per host, 100 max conns per host
- Timeouts: 90s idle conn timeout, 10s TLS handshake timeout, 1s expect-continue timeout
- Protocols: set via Protocols() (go-service HTTP protocol configuration)
TLS behavior:
- If cfg is non-nil it is assigned to [Transport.TLSClientConfig].
- If cfg is nil, the standard library defaults apply.
Types ¶
type ChainedHandler ¶ added in v2.407.0
ChainedHandler is an alias for negroni.Handler.
type ChainedHandlers ¶ added in v2.407.0
ChainedHandlers is an alias for negroni.Negroni.
func NewChainedHandlers ¶ added in v2.407.0
func NewChainedHandlers(handlers ...ChainedHandler) *ChainedHandlers
NewChainedHandlers constructs an HTTP middleware chain.
type Client ¶ added in v2.21.0
Client is an alias for net/http.Client.
It is provided so go-service code can depend on a consistent import path while preserving standard library semantics.
type ClosingRoundTripper ¶ added in v2.466.0
ClosingRoundTripper adapts a function to RoundTripper while making request-body ownership explicit.
The function's third return value reports whether ClosingRoundTripper should close req.Body before returning. Return true when the function rejects the request locally without delegating to another RoundTripper. Return false after delegating because the delegated RoundTripper owns the request body.
type Handler ¶ added in v2.8.0
Handler is an alias for net/http.Handler.
It is provided so go-service code can depend on a consistent import path while preserving standard library semantics.
func MaxBytesHandler ¶ added in v2.331.0
MaxBytesHandler wraps h so inbound request bodies are limited to n bytes.
This is a thin wrapper around net/http.MaxBytesHandler.
func NewNotFoundHandler ¶ added in v2.396.0
func NewNotFoundHandler(mux *ServeMux, pool *sync.BufferPool, handlers ...NotFoundHandler) Handler
NewNotFoundHandler wraps mux and lets handlers replace generated 404 responses.
Non-404 mux responses are flushed unchanged. This preserves method handling such as 405 Method Not Allowed while still allowing MVC, REST, or RPC packages to provide typed not-found responses.
func NewTelemetryHandler ¶ added in v2.589.0
NewTelemetryHandler wraps handler with OpenTelemetry instrumentation when tracing or metrics are enabled.
type HandlerFunc ¶ added in v2.22.0
type HandlerFunc = http.HandlerFunc
HandlerFunc is an alias for net/http.HandlerFunc.
It is provided so go-service code can depend on a consistent import path while preserving standard library semantics.
type Header ¶ added in v2.21.0
Header is an alias for net/http.Header.
It is provided so go-service code can depend on a consistent import path while preserving standard library semantics.
type MaxBytesError ¶ added in v2.331.0
type MaxBytesError = http.MaxBytesError
MaxBytesError is an alias for net/http.MaxBytesError.
It is returned when MaxBytesReader or MaxBytesHandler observes an inbound request body exceeding the configured byte limit.
type NotFoundHandler ¶ added in v2.396.0
type NotFoundHandler func(res ResponseWriter, req *Request) bool
NotFoundHandler handles an unmatched mux request.
It returns true when it has written a response. Returning false lets the next handler decide.
type Request ¶ added in v2.21.0
Request is an alias for net/http.Request.
It is provided so go-service code can depend on a consistent import path while preserving standard library semantics.
func NewRequestWithContext ¶ added in v2.21.0
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)
NewRequestWithContext constructs a new outgoing HTTP request with ctx.
This is a thin wrapper around net/http.NewRequestWithContext. The returned request is canceled when ctx is canceled.
type Response ¶ added in v2.21.0
Response is an alias for net/http.Response.
It is provided so go-service code can depend on a consistent import path while preserving standard library semantics.
type ResponseWriter ¶ added in v2.22.0
type ResponseWriter = http.ResponseWriter
ResponseWriter is an alias for net/http.ResponseWriter.
It is provided so go-service code can depend on a consistent import path while preserving standard library semantics.
type RoundTripper ¶ added in v2.21.0
type RoundTripper = http.RoundTripper
RoundTripper is an alias for net/http.RoundTripper.
It is provided so go-service code can depend on a consistent import path while preserving standard library semantics.
type RoutePolicy ¶ added in v2.643.0
type RoutePolicy struct {
// contains filtered or unexported fields
}
RoutePolicy stores route policy used by HTTP transport middleware.
Route registration code records policy here so middleware can make exact route decisions without inferring intent from path substrings. RoutePolicy is intended to be populated during startup before serving requests.
func NewRoutePolicy ¶ added in v2.643.0
func NewRoutePolicy() *RoutePolicy
NewRoutePolicy constructs an empty route policy registry.
func (*RoutePolicy) AllowUnauthenticated ¶ added in v2.643.0
func (r *RoutePolicy) AllowUnauthenticated(pattern string)
AllowUnauthenticated marks pattern as not requiring transport token authentication.
func (*RoutePolicy) IsOperation ¶ added in v2.643.0
func (r *RoutePolicy) IsOperation(req *Request) bool
IsOperation reports whether req targets a registered operation path.
func (*RoutePolicy) IsUnauthenticated ¶ added in v2.643.0
func (r *RoutePolicy) IsUnauthenticated(req *Request) bool
IsUnauthenticated reports whether req targets a route that does not require transport token authentication.
func (*RoutePolicy) Operation ¶ added in v2.643.0
func (r *RoutePolicy) Operation(pattern string)
Operation marks pattern as a service-owned operation path.
Operation matching is path-only so method mismatches can reach the mux and receive normal method handling.
type Router ¶ added in v2.643.0
type Router struct {
// contains filtered or unexported fields
}
Router registers HTTP handlers and their route policy on a mux.
func NewRouter ¶ added in v2.643.0
func NewRouter(mux *ServeMux, routePolicy *RoutePolicy) *Router
NewRouter constructs a Router backed by mux and routePolicy.
func (*Router) HandleOperation ¶ added in v2.643.0
HandleOperation registers handler and marks pattern as a service-owned operation path.
func (*Router) HandleOperationFunc ¶ added in v2.643.0
func (r *Router) HandleOperationFunc(pattern string, handler HandlerFunc)
HandleOperationFunc registers handler and marks pattern as a service-owned operation path.
func (*Router) HandleUnauthenticated ¶ added in v2.643.0
HandleUnauthenticated registers handler and marks pattern as not requiring transport token authentication.
type ServeMux ¶ added in v2.5.0
ServeMux is an alias for net/http.ServeMux.
It is provided so go-service code can depend on a consistent import path while preserving standard library semantics.
func NewServeMux ¶ added in v2.7.0
func NewServeMux() *ServeMux
NewServeMux constructs a new HTTP request multiplexer.
This is a thin wrapper around net/http.NewServeMux.
type Server ¶
Server is an alias for net/http.Server.
It is provided so go-service code can depend on a consistent import path while preserving standard library semantics.
func NewServer ¶
NewServer constructs an HTTP server with common timeout defaults and supported protocol settings.
Timeouts are derived from options first (if present) and fall back to the provided timeout value:
- read_timeout
- write_timeout
- idle_timeout
- read_header_timeout
Additional low-level server tuning may be provided through options using:
- max_header_bytes
Protocols are configured via Protocols().
Note: options.NonNegativeDuration uses MustParseDuration under the hood; invalid or negative option values will panic at server construction time.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package body provides request-body handling helpers for HTTP handlers.
|
Package body provides request-body handling helpers for HTTP handlers. |
|
Package client provides a content-aware HTTP client wrapper used by go-service.
|
Package client provides a content-aware HTTP client wrapper used by go-service. |
|
Package config contains HTTP transport configuration types used by go-service.
|
Package config contains HTTP transport configuration types used by go-service. |
|
Package content provides HTTP content negotiation helpers used by go-service.
|
Package content provides HTTP content negotiation helpers used by go-service. |
|
Package errors provides HTTP-specific error helpers for go-service.
|
Package errors provides HTTP-specific error helpers for go-service. |
|
Package events provides CloudEvents HTTP helpers behind the go-service import path.
|
Package events provides CloudEvents HTTP helpers behind the go-service import path. |
|
Package media defines common HTTP media type constants used by go-service.
|
Package media defines common HTTP media type constants used by go-service. |
|
Package meta provides HTTP-specific context metadata helpers and middleware for go-service.
|
Package meta provides HTTP-specific context metadata helpers and middleware for go-service. |
|
Package mvc provides a small MVC-style HTML rendering layer for go-service HTTP servers.
|
Package mvc provides a small MVC-style HTML rendering layer for go-service HTTP servers. |
|
Package rest provides REST-style HTTP handler registration and client helpers for go-service.
|
Package rest provides REST-style HTTP handler registration and client helpers for go-service. |
|
Package rpc provides RPC-style HTTP handler registration and client helpers for go-service.
|
Package rpc provides RPC-style HTTP handler registration and client helpers for go-service. |
|
Package server provides HTTP server adapters and lifecycle wiring for go-service.
|
Package server provides HTTP server adapters and lifecycle wiring for go-service. |
|
Package status provides helpers for working with HTTP status codes and status errors in go-service.
|
Package status provides helpers for working with HTTP status codes and status errors in go-service. |
|
Package telemetry provides minimal, stable helpers for wiring OpenTelemetry instrumentation into net/http clients and servers.
|
Package telemetry provides minimal, stable helpers for wiring OpenTelemetry instrumentation into net/http clients and servers. |