Documentation
¶
Overview ¶
Package httpx is the HTTP middleware bundle shared by every HB Labs service. Provides the standard outermost-middleware chain (request-id propagation, panic recovery, context-bound logger) that every service is expected to mount.
Wire order from outermost to innermost:
secheaders → httpx.RequestID → httplog → httpx.Recover → handler
secheaders sets policy headers on EVERY response (including the 500 from Recover). RequestID resolves request-id and device-id before any logging middleware runs so log lines carry them. httplog records exactly one access entry per request — placed outside Recover so the entry still fires for panicked requests (Recover converts the panic into a normal 500 before httplog sees the response). Recover is innermost so any handler panic is caught inside the chain and never tears down the goroutine.
Index ¶
- Constants
- func AccessLog(opts AccessLogOptions) func(http.Handler) http.Handler
- func Chain(mws ...Middleware) chain
- func ClientIP(r *http.Request) string
- func ClientIPTrusted(r *http.Request, set *CIDRSet) string
- func ContextLogAttrs(ctx context.Context) []log.Attr
- func DecodeJSON(w http.ResponseWriter, r *http.Request, dst any, maxBytes int64) bool
- func DetectBot(ua string) string
- func DeviceIDFromContext(ctx context.Context) string
- func FallbackSitemapURLs(domain string) []string
- func IntParam(values url.Values, key string, def int) int
- func IsTrustedProxy(ip net.IP, trusted []*net.IPNet) bool
- func NewFetchClient(opts FetchOptions) *http.Client
- func NewHandler() *handlerBuilder
- func ParseCIDRs(cidrs ...string) ([]*net.IPNet, error)
- func ParseRobotsSitemaps(body []byte) []string
- func QuietPaths(patterns ...string) func(r *http.Request) log.Level
- func Recover(next http.Handler) http.Handler
- func RequestID(base *log.Logger) func(http.Handler) http.Handler
- func RequestIDFromContext(ctx context.Context) string
- func RequireServiceToken(next http.Handler) http.Handler
- func RobotsCandidates(domain string) []string
- func WithDeviceID(ctx context.Context, id string) context.Context
- func WithRequestID(ctx context.Context, id string) context.Context
- func WriteError(w http.ResponseWriter, status int, msg string)
- func WriteJSON(w http.ResponseWriter, status int, v any)
- type AccessLogOptions
- type CIDRSet
- type ErrorResponse
- type FetchOptions
- type FetchResult
- type Middleware
- type SSEHub
- type SitemapDiscoveryResult
- type SitemapEntry
Constants ¶
const ( HeaderRequestID = constants.HeaderRequestID HeaderDeviceID = constants.HeaderDeviceID CookieDeviceID = constants.CookieDeviceID )
Re-exports of the canonical names from core/constants so callers (and tests) can refer to them through this package without importing constants directly. The strings themselves live in core/constants — single source of truth.
const CloudflareIPsURL = "https://api.cloudflare.com/client/v4/ips"
CloudflareIPsURL is the official endpoint Cloudflare publishes for their proxy IP ranges (https://api.cloudflare.com/client/v4/ips). One unauthenticated GET returns both IPv4 + IPv6 CIDRs as JSON, edge-cached so the call is essentially free for both us and CF.
const DefaultFetchAccept = "text/html,application/xml,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.8"
DefaultFetchAccept matches the Accept header a normal browser sends. Generic on purpose: a sitemap (application/xml), a robots.txt (text/plain), and a page (text/html) all flow through one call site, and a server that Vary's by Accept returning 406 for an unfamiliar value defeats the purpose.
const DefaultFetchUserAgent = "HB Labs Fetch/1.0 (+https://hblabs.co)"
DefaultFetchUserAgent identifies the platform's outbound fetches to upstream operators inspecting their access logs. Embeds an https://hblabs.co URL so a curious admin can find the platform without guessing. Override per-call via FetchOptions.UserAgent when a service has a more specific identity to advertise (e.g. the service-ingest crawler).
Variables ¶
This section is empty.
Functions ¶
func AccessLog ¶
func AccessLog(opts AccessLogOptions) func(http.Handler) http.Handler
AccessLog is the access-log middleware shared by every HTTP service. It emits one structured slog record per request with the data we actually look at when something goes wrong behind Cloudflare:
level=info msg=http method=GET path=/de/ status=200 duration=1.4ms
ip=… cf_country=… cf_ray=… cf_ip=… xri=… xff=… ua="…"
`ip` is the resolved client IP (see ClientIP). The raw CF-Connecting-IP / X-Real-IP / X-Forwarded-For values stay alongside so we can spot header spoofing or a misconfigured proxy — if cf_ip and ip disagree, something is wrong upstream. Missing headers print as `-` so a `grep cf_country=` always matches.
Each service decides per-route verbosity with AccessLogOptions.Level: noisy paths (kubelet probes, embedded asset fetches) drop to Debug so they only surface when LOG_LEVEL=debug is set; the rest stays at Info. This keeps production logs clean without losing the ability to inspect probes when troubleshooting.
return httpx.AccessLog(httpx.AccessLogOptions{
Level: httpx.QuietPaths("/healthz", "/static/*", "/favicon.*"),
})(mux)
The middleware writes to log.Default() (slog.Default() under the hood), which after the standard log.New + slog.SetDefault wiring at boot is the service-tagged logger. No Logger override field by design — services that want access logs in a separate sink can wrap or tee at the slog handler layer.
func Chain ¶
func Chain(mws ...Middleware) chain
Chain composes middleware in execution order — the FIRST listed middleware wraps the rest, so it sees the request first and the response last. Terminate the chain with .Then(handler):
handler := httpx.Chain(
secheaders.Middleware(secheaders.Options{}),
httpx.RequestID(nil),
httpx.AccessLog(opts),
httpx.Recover,
).Then(siteHandler)
Reads top-to-bottom matching execution order. Compare to the equivalent nested-call form, which reads inside-out and reverses the visual flow:
handler := secheaders.Middleware(...)(httpx.RequestID(nil)(
httpx.AccessLog(opts)(httpx.Recover(siteHandler))))
The returned value's only public surface is Then; the chain is applied at that point and a fresh http.Handler comes out.
func ClientIP ¶
ClientIP returns the best-guess origin IP using the preference chain CF-Connecting-IP → X-Real-IP → X-Forwarded-For[0] → RemoteAddr. Behind Cloudflare the only fully trustworthy value is CF-Connecting-IP (Cloudflare strips and re-sets it on every request); the others are kept as fallbacks for non-Cloudflare deployments. For X-Forwarded-For we take the first comma-separated value (the original client; the rest are intermediate proxies).
Exported because rate limiting, audit logs and geo lookups all need the same answer — keeping the logic here means every service agrees on what "the client IP" means.
func ClientIPTrusted ¶
ClientIPTrusted is the security-aware version of ClientIP. It only honours proxy headers (CF-Connecting-IP, X-Real-IP, XFF) when r.RemoteAddr falls inside the trusted set; otherwise it returns the raw RemoteAddr (the actual TCP peer) so an attacker who bypasses the proxy can't lie in the access log.
set == nil OR set with no CIDRs loaded yet means "no proxies trusted" — equivalent to always returning RemoteAddr. To get the legacy permissive behaviour, call ClientIP instead.
func ContextLogAttrs ¶
ContextLogAttrs returns the log Attrs derived from values the RequestID middleware put into ctx. Use as the value for AccessLogOptions.ContextAttrs so access log lines carry the same correlation fields as the per-request logger:
httpx.AccessLog(httpx.AccessLogOptions{
ContextAttrs: httpx.ContextLogAttrs,
})
Empty slice (not nil) when nothing is attached, so the caller can safely append to it without nil checks.
Note: WithLogger / LoggerFromContext live in core/log, not here, so that package owns every logger-related helper. httpx imports core/log to attach the per-request logger to ctx.
func DecodeJSON ¶
DecodeJSON reads the request body into dst, capping it at maxBytes and rejecting unknown fields (so a typo'd or extra key is a 400, not a silently-dropped value). On any failure it writes the canonical 400 ErrorResponse and returns false; the caller's branch reads as one line:
if !httpx.DecodeJSON(w, r, &req, maxBody) { return }
It owns the MaxBytesReader + DisallowUnknownFields + decode dance that every JSON-accepting handler in this repo would otherwise repeat.
func DetectBot ¶
DetectBot returns a short identifier for the crawler / bot behind a given User-Agent string. Match is by case-insensitive substring; the table is ordered so more specific identifiers win over the generic family (e.g. ChatGPT-User vs GPTBot are kept separate). Unknown / browser / empty UAs return "-" so the field is always safe to grep for an exact bot name.
Coverage focuses on bots that actually show up in real access logs: search-engine crawlers, social-media link unfurlers, LLM training & retrieval crawlers, and a handful of SEO scrapers. Easy to extend — just add a {needle, name} pair, mindful of order.
func DeviceIDFromContext ¶
DeviceIDFromContext returns the device-id stored in ctx, or "" if none is present. Callers that need a value either way should prefer "-" over "" for log lines — see ContextLogAttrs.
func FallbackSitemapURLs ¶
FallbackSitemapURLs returns the paths a discoverer probes when robots.txt is unreachable OR returns no Sitemap: directives. /sitemap.xml at the root is the universal convention; /sitemap_index.xml covers the (older) WordPress-Yoast layout that some properties still ship.
https is tried first (the 2026 norm); the http variants are the tail fallback for the long tail of sites that never moved to TLS — without them an http-only site that relies on the conventional /sitemap.xml (no Sitemap: directive in robots) would never be discovered, since every https probe fails on a box with no 443 listener. For an https site the http probes are harmless: they 404 fast or 301 to the https URL already tried.
func IntParam ¶
IntParam reads values[key] as a base-10 int. Empty values and values that fail to parse fall back to def — the caller picks a sensible default once and never has to branch on "missing vs malformed" again.
Why "fall back" rather than "return error": the typical caller is a list / autocomplete endpoint where a malformed ?page=abc from a confused client should serve page 1, not 400 the request and break the UI. Endpoints that need strict parsing (eg a job id) should pull the raw value and validate explicitly.
func IsTrustedProxy ¶
IsTrustedProxy reports whether ip falls inside any of the trusted CIDRs. nil/empty trusted means "trust nothing" — callers should treat that as "no proxy headers honoured".
func NewFetchClient ¶
func NewFetchClient(opts FetchOptions) *http.Client
NewFetchClient builds a goroutine-safe *http.Client tuned for one-shot outbound GETs with a bounded redirect chain. The Timeout is baked into the client (cleanest cancellation guarantee across all sub-stages); the User-Agent / Accept headers are NOT — those are applied per request inside FetchURL so a test can override one call without rewiring the client.
func NewHandler ¶
func NewHandler() *handlerBuilder
NewHandler starts a fluent middleware composition for HB Labs service stack. Add layers by chaining methods, then bind the inner handler with Merge:
handler := httpx.NewHandler().
Secure().
RequestID().
WithoutLogging(cfg.QuietPaths...).
WithRecover().
Merge(siteHandler)
Order: the FIRST method called wraps the rest. The example above produces a handler where Secure sees the request first, the inner siteHandler runs, and Recover catches any panic on the way out (converted to a 500). Layers compose top-to-bottom in the same order they appear in the call chain — the visual flow matches the request flow.
For arbitrary middleware outside the canonical set (rate limiter, OTel tracer, custom auth wrap), reach for Use(mw); for full AccessLog control beyond the WithoutLogging shorthand, use AccessLog(opts).
func ParseCIDRs ¶
ParseCIDRs converts a list of CIDR strings into *net.IPNet for fast membership checks. Whitespace and empty entries are ignored so the result of `strings.Split(env, ",")` can be passed verbatim even when the env var is unset.
Returns the first parse error verbatim — operators see the bad value with line context instead of a silent partial parse.
func ParseRobotsSitemaps ¶
ParseRobotsSitemaps extracts every `Sitemap: <url>` directive from a robots.txt body. Case-insensitive on the field name (the RFC is); URL preserved verbatim because Sitemap: directives are absolute by definition.
Returns a deduplicated list in source order. A robots.txt that declares the same sitemap twice (some CMS plugins do) shouldn't produce two fetches downstream.
Skips URLs that don't parse or that use a non-http(s) scheme — a misuse the caller doesn't want to retry-bomb on.
func QuietPaths ¶
QuietPaths returns an AccessLogOptions.Level function that demotes the listed paths to Debug and leaves everything else at Info. Patterns follow a tiny convention so a single env var can express both shapes:
- trailing "*" → prefix match (e.g. "/static/*", "/favicon.*")
- anything else → exact match (e.g. "/healthz")
Empty / whitespace-only patterns are ignored, so splitting a CSV env var on "," and passing the result is safe even if the var is unset.
patterns := strings.Split(envcfg.String("LOG_QUIET_PATHS",
"/healthz,/static/*,/favicon.*"), ",")
httpx.AccessLog(httpx.AccessLogOptions{Level: httpx.QuietPaths(patterns...)})
func Recover ¶
Recover catches panics from any downstream handler, logs them with a full stack trace using the per-request logger from the context (so request_id / device_id are attached automatically), and returns 500 with a generic body.
Without this middleware a panic in any handler would unwind the goroutine and leave the client with a closed connection or a torn HTTP/2 stream — symptomatically identical to a TCP reset from the operator's side and miserable to debug.
Place this innermost in the chain (just outside the application handler) so the access log middleware above sees a normal 500 response and still records the entry. If Recover were outside httplog, a panicked request would never reach LogAttrs and we'd lose the access log line for the worst kind of bug.
The response body is generic ("Internal Server Error") on purpose: leaking the panic message or the stack to the client helps attackers fingerprint internal layout. Detail is in the log already — that's where it belongs.
func RequestID ¶
RequestID is the standard outermost-app middleware. It resolves a request-id and a device-id, stores both in the request context, and echoes them back as response headers so callers can correlate.
Resolution rules:
request-id: prefer the X-Request-Id sent by the client (a reverse proxy, an iOS app, a script with its own correlation ID), else generate a fresh one. We always put it back in the request header too so downstream handlers/middleware that read headers (rather than the context) see the same value.
device-id: prefer the X-Device-Id header (native apps sending IDFV or equivalent), then the hbl_did cookie (browser clients who've been here before), else generate one and Set-Cookie it. The result persists across requests for browsers without any server-side state — exactly what RequestLog and analytics downstream want. The Set-Cookie's Domain comes from HB_COOKIE_DOMAIN: empty (host-only) on a laptop / custom domain, ".hblabs.co" in prod so every *.hblabs.co subdomain shares one device-id.
The middleware also attaches a slog.Logger pre-bound with both IDs to the context. Handlers retrieve it with httpx.Logger(ctx) so every line they emit carries request_id and device_id without having to re-attach them on each call.
`base` is the logger to derive the per-request logger from. Pass the same one set with log.SetDefault(log.New("svc")) at boot so handler logs inherit the service tag. nil → log.Default().
func RequestIDFromContext ¶
RequestIDFromContext returns the request-id stored in ctx by the RequestID middleware, or "" if none is present. "" rather than panicking so background workers (cron jobs, NATS consumers) that lack a request-id don't crash when reusing handler code paths.
func RequireServiceToken ¶
RequireServiceToken gates the wrapped handler behind the shared internal service token: the X-HB-Service-Token header must match HB_INTERNAL_SERVICE_TOKEN (constant-time compare). An empty configured token rejects every request, so the gate fails closed: internal access stays shut until the secret is provisioned.
This is the canonical service-to-service auth gate for internal (non public) routes. Any service wraps its internal subtree with it so the same shared secret works everywhere, e.g.
mux.Handle("/v1/admin/", httpx.RequireServiceToken(adminHandler))
The token is one shared secret across services in v1, a placeholder until real service identity (mTLS/SPIFFE). It is read from the env on every request (via envcfg) so a rotated secret takes effect without a restart once the pod's secret env is refreshed.
func RobotsCandidates ¶
RobotsCandidates returns the schemes-and-paths a discoverer should try when looking for a site's robots.txt, in priority order. https first because the vast majority of properties are TLS-only by 2026; the http fallback exists for the long tail that hasn't moved yet. /robots.txt at the root is the only path the RFC defines.
Accepts a bare domain ("example.com"), a scheme-prefixed host ("https://example.com"), or a host with a trailing slash — normalises all three to the same candidate set.
func WithDeviceID ¶
WithDeviceID attaches id to ctx.
func WithRequestID ¶
WithRequestID attaches id to ctx. Normally only the RequestID middleware calls this; tests and tools can call it directly when constructing a context without going through HTTP.
func WriteError ¶
func WriteError(w http.ResponseWriter, status int, msg string)
WriteError writes the canonical ErrorResponse with the given status and message. The convenience wrapper exists so handler branches read as one-liners — `httpx.WriteError(w, 400, "bad JSON")` instead of an inline ErrorResponse literal.
Pre-set headers (eg the `Allow` header on a 405) survive the call because WriteJSON only writes Content-Type before flushing — set them before calling WriteError and they land on the wire.
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, status int, v any)
WriteJSON serialises v at the given status with the canonical JSON Content-Type. On marshal failure the response degrades to a plain-text 500 via http.Error — that branch is meant to be unreachable in practice (every caller marshals a struct declared in this repo), but the fallback is here so a future addition doesn't silently truncate a response body.
Status MUST be set through this function (not via a manual w.WriteHeader before the call); the order Content-Type → WriteHeader → Write matters for proxies and httptest recorders alike.
Types ¶
type AccessLogOptions ¶
type AccessLogOptions struct {
// Level returns the log level for a request. nil = Info for all.
// Use this to demote noisy probes to Debug; the global slog
// logger's level threshold then decides what gets emitted.
Level func(r *http.Request) log.Level
// TrustedProxies is the dynamic CIDR set that may legitimately
// set CF-Connecting-IP / X-Real-IP / X-Forwarded-For. When
// non-nil, the access log's `ip` field falls back to RemoteAddr
// for any request whose TCP peer is NOT in the current snapshot
// — so an attacker who finds the origin can't spoof their IP in
// our logs or in any downstream component (rate limit, audit)
// keyed off ip.
//
// Pass an httpx.NewCloudflareCIDRSet() that has been Refresh()ed
// at boot and is being kept up to date by a periodic ticker.
// nil = trust every proxy header blindly (legacy behaviour, only
// fine when the origin is firewalled to the proxy at the network
// layer).
TrustedProxies *CIDRSet
// ContextAttrs returns Attrs appended to each access log line,
// derived from the request context. nil defaults to
// httpx.ContextLogAttrs (the request-id / device-id the
// RequestID middleware puts into context) — the canonical
// correlation fields every service wants, surfaced without
// per-call wiring. Pass an explicit func to add MORE (compose
// ContextLogAttrs with your own), or a func returning nil to
// suppress the defaults entirely.
ContextAttrs func(ctx context.Context) []log.Attr
// ExtraAttrs returns Attrs derived from the REQUEST itself
// (headers, method, path) rather than from context. Use it for
// genuinely service-specific fields the standard set doesn't
// cover. For the platform-standard caller fingerprint, prefer
// the ClientMeta toggle below — it's the same data every
// service would otherwise re-wire here. Runs after
// ContextAttrs, so its keys win on a collision. nil = none.
ExtraAttrs func(r *http.Request) []log.Attr
// ClientMeta, when true, appends the full core/clientmeta
// fingerprint as a nested `client` group (client.ip,
// client.user_agent, client.accept_language, client.app_version,
// client.sec_ch_ua*, the raw proxy chain, the Cloudflare geo
// headers). These are platform-standard request headers, so a
// service that wants the caller fingerprint flips this bool
// instead of re-wiring an ExtraAttrs hook with the same
// clientmeta plumbing.
//
// The group reuses the same resolved IP as the top-level `ip`
// field (honouring TrustedProxies), and clientmeta drops empty
// headers so a native-app call stays compact. Nesting under
// `client.*` keeps the keys distinct from the top-level request
// fields — no duplicate JSON keys.
ClientMeta bool
// Query, when true, appends the raw URL query string as a
// `query` field (e.g. query="q=trainer&sort=bytes_desc&page=2").
// Empty query strings are skipped so plain paths stay compact.
//
// OPT-IN on purpose: a query string can carry secrets on some
// endpoints (auth tokens, signed URLs in the URL itself), and
// access logs ship to long-lived sinks (Loki). Enable it only
// where the parameters are safe to log — filter/sort/pagination
// params on an internal API, not token-bearing public routes.
// If a service needs query logging on a route that MIGHT carry
// a secret, redact at the handler instead of flipping this on.
Query bool
}
AccessLogOptions configures AccessLog. Zero value = log every request at Info, with proxy headers trusted blindly. Set TrustedProxies in any production deployment behind a proxy.
type CIDRSet ¶
type CIDRSet struct {
// contains filtered or unexported fields
}
CIDRSet is a lock-free, periodically-refreshed view of a CIDR list — typically the Cloudflare proxy ranges. Reads (Snapshot) are an atomic.Pointer load, so the hot path on every request is a single pointer read + slice scan; writes (Refresh) replace the whole slice atomically so a concurrent reader sees either the old or new set, never a torn one.
Pair with a periodic ticker for daily refreshes; if Refresh fails the previous good snapshot stays put, so a CF outage doesn't degrade the trust boundary.
func NewCIDRSet ¶
NewCIDRSet builds a generic CIDRSet for any JSON endpoint that returns a Cloudflare-shaped body (`{result:{ipv4_cidrs,ipv6_cidrs}}`). For the standard CF endpoint use NewCloudflareCIDRSet.
httpClient may be nil; we build one with defaultCIDRFetchTimeout.
func NewCloudflareCIDRSet ¶
func NewCloudflareCIDRSet() *CIDRSet
NewCloudflareCIDRSet returns a CIDRSet wired to Cloudflare's official IPs endpoint. Refresh hasn't been called yet — invoke it (synchronously, with a timeout context) at boot so the first request already sees a populated set.
func (*CIDRSet) Refresh ¶
Refresh fetches the upstream CIDR list and atomically swaps the in-memory snapshot. Safe to call concurrently with Snapshot.
Errors leave the previous snapshot untouched — the caller (the ticker loop) keeps retrying on its retry cadence; meanwhile reads continue with whatever was last known good.
type ErrorResponse ¶
type ErrorResponse struct {
Error string `json:"error"`
}
ErrorResponse is the canonical JSON error envelope every service returns when a request fails. One field, one human-readable message, no nested codes or stack traces. The shape is part of the API contract for iOS / web clients — a client decoder hard-codes `{"error": string}` and doesn't need to branch per endpoint.
Why a struct rather than a free-form map: the field name is guaranteed at compile time, and any logging or middleware that wants to enrich the payload (eg add a request_id) can extend the struct in one place rather than chasing literals across every handler.
type FetchOptions ¶
type FetchOptions struct {
// Timeout caps the total time per request (DNS → headers →
// body). Zero leaves the http.Client default (no timeout) —
// almost never what you want for an outbound crawl, so pass
// an explicit value at the call site.
Timeout time.Duration
// MaxBodySize caps the response body in bytes. A response
// larger than the cap returns FetchResult.BodyTooLarge = true
// with Body = nil; the partial download is discarded so a
// later re-fetch with a higher cap remains meaningful.
MaxBodySize int64
// UserAgent overrides the User-Agent header. Empty falls back
// to DefaultFetchUserAgent.
UserAgent string
// Accept overrides the Accept header. Empty falls back to
// DefaultFetchAccept (a browser-shaped wildcard).
Accept string
// MaxRedirects overrides the redirect-chain cap. Zero falls
// back to defaultFetchMaxRedirects. Negative disables the
// cap (use carefully — a hostile upstream can loop forever).
MaxRedirects int
}
FetchOptions configures NewFetchClient and FetchURL. Zero values pick safe defaults (DefaultFetchUserAgent, DefaultFetchAccept, defaultFetchMaxRedirects, defaultFetchMaxBodySize) so a caller can pass FetchOptions{Timeout: 15 * time.Second} and get the rest for free.
type FetchResult ¶
type FetchResult struct {
// StatusCode is the HTTP status the upstream returned. Zero
// when the request never reached a response (transport error
// — see Err).
StatusCode int
// ContentType is the value of the upstream's Content-Type
// header, verbatim. Empty when no header was returned.
ContentType string
// Body is the response bytes, present only when the upstream
// returned a 2xx and the body fit under MaxBodySize. Nil in
// every other case (non-2xx, transport error, BodyTooLarge).
Body []byte
// SHA256Hex is the hex-encoded sha256 of Body. Computed
// inline while reading the body so callers that need it for
// content addressing don't pay a second pass. Empty when
// Body is nil.
SHA256Hex string
// BodyTooLarge is true when the upstream's response exceeded
// MaxBodySize. Surfaced as a flag (not an error) so the
// caller's classifier can distinguish "too big" from "broke"
// without parsing error messages.
BodyTooLarge bool
// Err is the raw transport-layer error when the request did
// not produce a 2xx-with-body result. Nil on success. The
// caller is expected to classify it (timeout, DNS, TLS, ...)
// using its own vocabulary.
Err error
}
FetchResult is the typed outcome of one FetchURL call. The caller drives behaviour off the fields rather than re-inspecting the *http.Response — the response body is already consumed and the connection closed by the time FetchURL returns.
Classification is the caller's job: this package returns (Err, StatusCode, BodyTooLarge) as neutral signals and lets the caller map them to its own closed vocabulary of error codes. That keeps httpx free of any one service's error taxonomy while still funnelling every fetch through one implementation.
func FetchURL ¶
func FetchURL(ctx context.Context, client *http.Client, opts FetchOptions, url string) FetchResult
FetchURL performs one bounded HTTP GET against url and returns a FetchResult. The caller-supplied client is usually built by NewFetchClient; reusing the same client across many calls amortises TLS handshake and connection-pool cost.
Returns:
- On transport error (DNS, TLS, timeout, ...): FetchResult{Err: ...} with StatusCode = 0 and Body = nil. The caller classifies Err however it wants.
- On non-2xx with no body limit hit: FetchResult{StatusCode: code, ContentType: ..., Body: nil, Err: an error describing the status}. The caller decides whether 4xx and 5xx mean different things.
- On 2xx with body over MaxBodySize: FetchResult{ BodyTooLarge: true, Body: nil}. The partial download is discarded.
- On 2xx success: FetchResult{StatusCode: 2xx, Body: bytes, SHA256Hex: hex, ContentType: ...}.
type Middleware ¶
Middleware is the canonical http middleware shape: a function that takes an http.Handler and returns an http.Handler. Aliased here so call sites read `[]httpx.Middleware{...}` instead of the raw `func(http.Handler) http.Handler` mouthful.
type SSEHub ¶
type SSEHub struct {
// contains filtered or unexported fields
}
SSEHub is a tiny in-process broadcaster: HTTP subscribers receive a Server-Sent Event whenever Broadcast() is called. No auth, no buffering of missed events, no per-subscriber state — designed to fan a single signal to a handful of connected browsers / agents without any back-pressure on the broadcaster.
Typical consumers: dev hot-reload (render/dev), admin live tailing of in-memory state, demo dashboards. Anything that needs guaranteed delivery, replay, or fan-in across pods should use NATS instead; SSEHub is intentionally minimal.
func NewSSEHub ¶
func NewSSEHub() *SSEHub
NewSSEHub returns an SSEHub with the default keep-alive — fine for any reasonable setup. Override the cadence with NewSSEHubWithKeepAlive when running behind a proxy with a shorter idle timeout, or pass 0 to disable keep-alive entirely.
func NewSSEHubWithKeepAlive ¶
NewSSEHubWithKeepAlive lets the caller override the keep-alive cadence. Pass 0 to disable keep-alive entirely (useful when the hub sits behind a proxy that already sends its own keepalives).
func (*SSEHub) Broadcast ¶
func (h *SSEHub) Broadcast()
Broadcast wakes every connected subscriber. Non-blocking — a slow subscriber whose channel is already full simply misses this event, which is fine for the use cases this hub targets: the next event catches up. SSEHub doesn't promise delivery, only liveness.
func (*SSEHub) ServeSSE ¶
func (h *SSEHub) ServeSSE(eventName string) http.HandlerFunc
ServeSSE returns an http.HandlerFunc that streams Broadcast events to subscribers as Server-Sent Events. eventName is the value written in `event:` lines (the browser ignores it for plain `onmessage`, but it's useful when filtering on event types).
type SitemapDiscoveryResult ¶
SitemapDiscoveryResult is the typed outcome of walking the robots.txt → sitemap discovery chain for one domain.
- RobotsURL is the URL the discoverer resolved robots.txt from. Empty when every candidate failed.
- RobotsBody is the robots.txt body verbatim (empty when unreachable). Exposed so the caller can persist it to its own audit store.
- SitemapURLs is the list of sitemap URLs to fetch next. Comes from `Sitemap:` directives in robots.txt when available, or from well-known fallback paths (`/sitemap.xml`, `/sitemap_index.xml`) when robots was empty / unreachable.
func DiscoverSitemap ¶
func DiscoverSitemap(ctx context.Context, client *http.Client, opts FetchOptions, domain string) SitemapDiscoveryResult
DiscoverSitemap walks the robots.txt → sitemap discovery chain for one domain using the supplied HTTP client and options. Composes RobotsCandidates + ParseRobotsSitemaps + FallbackSitemapURLs so a caller gets the full discovery in one call.
"Success" for robots.txt is a 2xx with a body; a 404 or any transport failure is treated as "site has no robots, that's fine, fall through to the fallback paths". A 5xx / DNS / timeout is treated the same way — discovery is best-effort, and recording "I couldn't read your robots" without giving up on the rest is the more useful behaviour for an audit-driven crawler.
SitemapURLs in the result is ALWAYS non-empty (it contains the well-known fallbacks when nothing else worked); whether those URLs actually resolve to a parseable sitemap is the caller's problem — DiscoverSitemap doesn't fetch them.
type SitemapEntry ¶
type SitemapEntry struct {
// Loc is the absolute URL of the resource. Empty entries are
// dropped by ParseSitemap.
Loc string
// LastMod is the upstream's last-modified hint, verbatim
// (W3C-DTF date or ISO-8601 timestamp). The caller is free to
// parse it or ignore it; leaving it as a string keeps the
// parser lossless and avoids forcing a time-format choice on
// every consumer.
LastMod string
}
SitemapEntry is one <url> from a sitemap.xml's urlset. Carries only the fields downstream crawlers actually use; the rest of the spec (changefreq, priority) is parsed but discarded.
func ParseSitemap ¶
func ParseSitemap(body []byte) (entries []SitemapEntry, nested []string, err error)
ParseSitemap parses a sitemap body and returns either the list of leaf entries or the list of nested sitemap URLs, dispatching on the root element:
- <urlset> → leaf entries (<url><loc>) [sitemaps.org XML]
- <sitemapindex> → nested sitemap URLs (<sitemap><loc>) [sitemaps.org index]
- <rss> → leaf entries (<item><link>) [RSS 2.0 feed]
- <feed> → leaf entries (<entry><link href>) [Atom 1.0 feed]
RSS 2.0 and Atom 1.0 are first-class sitemap formats per the sitemaps.org / Google spec — WordPress SEO plugins (All in One SEO, Yoast) often point robots.txt at a `sitemap.rss` feed instead of the XML urlset, so a crawler that only understood <urlset> would silently miss every WordPress site on a feed sitemap. The entry's link is the URL; pubDate / updated maps to LastMod.
Exactly one of the two return slices is non-empty on success; both are empty on an unrecognised root. Recursion is the caller's job: walk `nested` with the same parser, applying a depth cap (the right value depends on the crawler's policy, not the parser).
Returns an error only on hard XML parse failures — an empty document, or unrecognised root, returns (nil, nil, nil) so a caller can treat "found nothing" uniformly with "the upstream served a 404" without branching on error type.