http

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 39 Imported by: 0

Documentation

Overview

Package http ports packages/chord/src/next-node/http (Chord v2's HTTP component, slice 10 §2): a Web-standard `fetch` handler built from the routes, wraps and sockets plugins contribute to the registry `Http`, with the security baseline on by default, Chord's own listener, an upgrade adapter and the request conversion for apps that mount it. `index.ts` is designed out: Go imports the package, and what it exported is exported here. JavaScript's Fetch and DOM types are Go's net/http types; the WebSocket `ws` is gorilla/websocket behind WebSocket (websocket.go).

Where Go's net/http server differs from Node's observably, each file says so under "Forced Go differences" (node.go lists the listener's).

Index

Constants

View Source
const (
	ScopeOwn = "own"
	ScopeAll = "all"
)

Scopes of a wrap.

View Source
const (
	WebSocketConnecting  = 0
	WebSocketOpenState   = 1
	WebSocketClosing     = 2
	WebSocketClosedState = 3
)

WebSocket ready states, as `ws` numbers them.

Variables

View Source
var Authenticators = must(registries.DefineRegistry[Authenticator, []AuthenticatorEntry]("chord.http.authenticators", registries.DefineRegistryOptions{Version: 1}))

Authenticators is the registry of authenticators (served by `http.facet`).

Http is the registry the HTTP component defines and serves (`http.facet`, plugin `chord.http`).

View Source
var HttpFollower = must(contracts.Local("chord.http.follower", contracts.LocalDeclaration{Version: 1, Params: contracts.Params{}, Members: []contracts.LocalEntry{}}))

HttpFollower is the follower: a host-lifetime object of plugin `chord.http` that follows the router. It has no Pi counterpart as a type: Pi's `#follow` watches the router on the event loop; Go's sources are followed from inside the host's sections (an `OnNative` routine).

View Source
var HttpListener = must(contracts.Local("chord.http.listener", contracts.LocalDeclaration{Version: 1, Params: contracts.Params{}, Members: []contracts.LocalEntry{}}))

HttpListener is the listener: a host-lifetime object of plugin `chord.http` whose native is Chord's own server.

View Source
var UNCARRIED = map[string]bool{"CONNECT": true, "TRACE": true, "TRACK": true}

UNCARRIED are the methods a Web `Request` cannot carry (the Fetch standard's forbidden methods): answered 501 at the wire, a route for one refused at compose.

Functions

func Cookie(name, value string, options CookieOptions) string

Cookie is a signed `Set-Cookie` value for name and value (put it in a response's `headers`, `Set-Cookie`). With MaxAge its expiry is signed with it: a copy read back later is refused; without, it holds until the secret changes.

func HeaderGet

func HeaderGet(headers nethttp.Header, name string) (string, bool)

HeaderGet is `Headers.get`: the values of name joined with ", ", false when there is none.

func ReadCookie

func ReadCookie(request HttpRequest, name, secret string) (string, bool)

ReadCookie is the value of cookie name on request when its signature with secret holds and its signed expiry has not passed; false otherwise.

Types

type Admission

type Admission interface {
	// contains filtered or unexported methods
}

Admission is what admit decides: *Admitted or *Refused.

type Admitted

type Admitted struct {
	Provenance Provenance
	Origin     string
	// Framer is the origin allowed to frame it, "" for none.
	Framer string
	// Allowed is the allowed host it came through, "" for none: its connections end when that host leaves.
	Allowed string
	// Relay is the relay that verified it, nil for none: its connections end when that relay leaves.
	Relay *HttpRelay
}

Admitted is an admitted request: its provenance, its own origin, the origin allowed to frame it (a relay's), how it came.

type Answer

type Answer struct {
	Status  int
	Headers *AnswerHeaders
	Text    string
	Stream  *PulledBody
}

Answer is what the component answers: a status, its headers, and a whole body (Text, UTF-8), a pulled one (Stream), or none (both empty).

type AnswerHeaders

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

AnswerHeaders are a response's headers as the component builds them: by lowercased name, each value checked when set.

func NewAnswerHeaders

func NewAnswerHeaders() *AnswerHeaders

NewAnswerHeaders is an empty set of headers.

func (*AnswerHeaders) Delete

func (h *AnswerHeaders) Delete(name string)

Delete removes name.

func (*AnswerHeaders) Get

func (h *AnswerHeaders) Get(name string) (string, bool)

Get is the values of name joined with ", ", false without it.

func (*AnswerHeaders) Has

func (h *AnswerHeaders) Has(name string) bool

Has is whether name is set.

func (*AnswerHeaders) Lines

func (h *AnswerHeaders) Lines() []HeaderLine

Lines is each header line, in order.

func (*AnswerHeaders) Set

func (h *AnswerHeaders) Set(name string, values ...string) error

Set sets name to values (several values: one header line each, as `Set-Cookie` needs), replacing a same-named one; it returns a *HeaderError for a name or value HTTP cannot carry.

type Authenticator

type Authenticator func(request HttpRequest, ctx context.Context) (data.Principal, error)

Authenticator is who request is, or nil (anonymous here, maybe another authenticator knows).

type AuthenticatorEntry

type AuthenticatorEntry struct {
	Plugin       string
	Authenticate Authenticator
}

AuthenticatorEntry is an authenticator with its plugin, as the component asks it.

type CloseEvent

type CloseEvent struct {
	Code   int
	Reason string
}

CloseEvent is the data of a `close` event: the close code (1006 for a connection that ended without a close frame) and reason.

type Connection

type Connection struct {
	LocalAddress  string
	LocalPort     int
	RemoteAddress string
}

Connection is the connection a request arrived on, as its listener knows it (a mounted handler passes what it has).

type CookieOptions

type CookieOptions struct {
	// Secret is the key it is signed with (HMAC-SHA256).
	Secret string
	// Request is the request it answers: a remote one gets `Secure`.
	Request HttpRequest
	// SameSite is `Strict` by default; `Lax` lets a top-level navigation from another site carry it.
	SameSite SameSite
	// MaxAge is the seconds until it expires; nil: a session cookie.
	MaxAge *float64
}

CookieOptions is what `cookie` takes besides the name and the value.

type CspEntry

type CspEntry struct {
	Directive string
	Sources   []string
}

CspEntry is extra CSP sources of one directive (`img-src` → `https://cdn.example.com`).

type DefaultHeaders

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

DefaultHeaders are the default headers of one component's responses. The CSP around the nonce is kept per router and origin for local and allowed-host requests (a bounded set: the hosts contributions name); a relayed request's origins come from its relay and are never kept.

func NewDefaultHeaders

func NewDefaultHeaders() *DefaultHeaders

NewDefaultHeaders is an empty set of policies.

func (*DefaultHeaders) Of

func (d *DefaultHeaders) Of(admitted *Admitted, router *Router, nonce string) (*AnswerHeaders, error)

Of is the default headers of a response to a request admitted as admitted (nil: refused before admission), with router's framers and CSP sources (nil before the router is resolved), its CSP allowing scripts with nonce. It returns a *HeaderError when a contributed CSP source is no header value (a CR, a LF): the headers of a request refused before admission or a router never are.

type FileResponseOptions

type FileResponseOptions struct {
	// Download is the name it is saved under.
	Download string
	// Inline is shown in the browser instead of saved (an image, a video), with a `sandbox` CSP.
	Inline bool
	// Root is the directory the file must lie in once its symbolic links are resolved: one outside it (a link out) is
	// refused 403. Without it the path is trusted (a plugin's own file).
	Root string
	// Ranges is whether a single range is answered 206 (audio and video seek with it).
	Ranges bool
	// Mime is the type; by default from the extension (text, images, audio, video), else `application/octet-stream`.
	Mime string
}

FileResponseOptions is what `fileResponse` takes besides the path.

type Handler

type Handler interface {
	// Serve serves a request: it never fails.
	Serve(incoming Incoming, connection Connection) Served
	// Refusal is the answer for a request refused before it could be made one (default headers only).
	Refusal(status int) Answer
	// Upgrade handles a request asking for an upgrade (Node's `upgrade` event).
	Upgrade(w nethttp.ResponseWriter, request *nethttp.Request)
}

Handler is what the listener needs of the component.

type HeaderError

type HeaderError struct{ Message string }

HeaderError is Pi's `TypeError` for a header name or value HTTP cannot carry.

func (*HeaderError) Error

func (e *HeaderError) Error() string

type HeaderLine

type HeaderLine struct{ Name, Value string }

HeaderLine is one header line: the name as set and a value.

type HookName

type HookName string

HookName is a hook the component calls.

const (
	HookAuthenticate HookName = "authenticate"
	HookRelay        HookName = "relay"
	HookLinksOptions HookName = "links.options"
)

type HttpComponent

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

HttpComponent is the running component.

func CreateHttp

func CreateHttp(h host.Host, options HttpOptions, ctx context.Context) *HttpComponent

CreateHttp builds the HTTP component on h (a request's scope is a `host.Root` with its principal).

func (*HttpComponent) Close

func (c *HttpComponent) Close(ctx context.Context)

Close refuses new requests and upgrades (503), closes sockets and links (1001, terminated at CloseTimeout), waits for running requests up to CloseTimeout (an aborted ctx: not at all), then seals them. Run it before `host.Close`, which seals every request's scope at once (the listener's close runs it then, too late to drain).

func (*HttpComponent) Facet

func (c *HttpComponent) Facet() host.Facet

Facet is its facet (plugin `chord.http`): serves `Http` and `Authenticators`, and with Listen the listener, a host-lifetime object. The app loads it among its core facets, the same object at every reload.

func (*HttpComponent) Fetch

func (c *HttpComponent) Fetch(request *nethttp.Request, connection Connection) *nethttp.Response

Fetch answers a request (an app's own server mounts it); connection is what the server knows of the socket: without LocalAddress and LocalPort no request is local. Requests before the publication wait for it (503 past the host's `readyTimeout`).

func (*HttpComponent) Listening

func (c *HttpComponent) Listening(ctx context.Context) (ListenAddress, error)

Listening is where the listener listens, once it does (the real port when Listen.Port was 0); an error once the component closed or ctx ended.

func (*HttpComponent) Refusal

func (c *HttpComponent) Refusal(status int) Answer

Refusal is the answer for a refused or failed request, outside any scope, with the default headers.

func (*HttpComponent) Serve

func (c *HttpComponent) Serve(request Incoming, connection Connection) Served

Serve serves request: its answer, and what its consumer calls once the body is written or abandoned. It never fails: whatever fails answers (503 before the publication or while closing, 403, 404, 500 reported).

func (*HttpComponent) Upgrade

func (c *HttpComponent) Upgrade(w nethttp.ResponseWriter, request *nethttp.Request)

Upgrade is the upgrade adapter: the app's handler calls it for a request asking for an upgrade (the links endpoint and plugin sockets). It tracks the upgrade from its arrival: refused while closing, else admitted and checked, then handed out.

type HttpContribution

type HttpContribution struct {
	// Routes by `"METHOD /pattern"`: exact segments, `:name`, a trailing `/*`.
	Routes []HttpRouteEntry
	Wraps  []HttpWrap
	// Sockets are plugin sockets by pattern (no method).
	Sockets []HttpSocketEntry
	// MaxPayload is the largest frame this contribution's sockets accept; 1 MiB by default (0).
	MaxPayload int
	// Hosts are allowed besides loopback, as the client names them (`notes.example.com`): requests through them are https.
	Hosts []string
	// Framers are origins allowed to frame the app's pages (CSP `frame-ancestors`).
	Framers []string
	// Relays are relays whose forwarded requests are admitted (verified) on loopback.
	Relays []*HttpRelay
	// Csp is extra CSP sources by directive.
	Csp []CspEntry
}

HttpContribution is what a plugin contributes to `Http`: a plain value, or a writable of one (its change recomposes the router).

type HttpError

type HttpError struct {
	Kind    HttpErrorKind
	Pattern string
	Plugin  string
	Name    string
	Hook    HookName
	Error   error
}

HttpError is what the component reports: route_failed (Pattern, Plugin), wrap_failed (Name, Plugin), socket_failed (Pattern, Plugin), response_failed (Pattern: a response that could not be made or read whole) and hook_failed (Hook, and the Plugin of a contributed hook; none for the app's `links.options`).

type HttpErrorKind

type HttpErrorKind string

HttpErrorKind tells what an HttpError reports.

const (
	ErrRouteFailed    HttpErrorKind = "route_failed"
	ErrWrapFailed     HttpErrorKind = "wrap_failed"
	ErrSocketFailed   HttpErrorKind = "socket_failed"
	ErrResponseFailed HttpErrorKind = "response_failed"
	ErrHookFailed     HttpErrorKind = "hook_failed"
)

type HttpFailure

type HttpFailure struct {
	Status  int
	Message string
}

HttpFailure is a failure that answers its request with Status when it escapes a route (400 malformed, 413 too large).

func NewHttpFailure

func NewHttpFailure(status int, message string) *HttpFailure

NewHttpFailure is `new HttpFailure(status, message)`.

func (*HttpFailure) Error

func (f *HttpFailure) Error() string

type HttpOptions

type HttpOptions struct {
	// Listen is where Chord's own listener listens; nil: no listener (an app mounting `Fetch`). Port 0 picks one.
	Listen *ListenAddress
	// Links is the links endpoint: its path, and each socket's options; nil: none.
	Links *LinksOptions
	// CloseTimeout is how long `Close` waits for running requests and closing sockets: 30 s by default (0).
	CloseTimeout time.Duration
	OnError      func(HttpError)
}

HttpOptions is what `CreateHttp` takes: the app's settings, fixed for the component's life (changing one is a restart).

type HttpRelay

type HttpRelay struct {
	Name   string
	Verify func(request *nethttp.Request) (*RelayVerified, error)
}

HttpRelay is a relay (p2's Radius): a forwarder on loopback that sends forwarded headers. Verify recognizes its requests (a secret header, a signature) and names the origin the request came from and the origin allowed to frame it.

type HttpRequest

type HttpRequest interface {
	Method() string
	// Path is the path, without the query, percent-encoded, its dot segments resolved (by the URL parser).
	Path() string
	// Params are the matched pattern's params, percent-decoded (`*` for the rest of a `/*` pattern).
	Params() map[string]string
	Query() *URLSearchParams
	// Headers are the request's headers; read only.
	Headers() nethttp.Header
	// Origin is `http://<host>` on loopback, `https://<host>` for an allowed host, a relay's origin for a relayed request.
	Origin() string
	// Provenance is where it came from (decision "The HTTP component's security baseline" (1), "Relays").
	Provenance() Provenance
	// Nonce is the server's script nonce: a page's inline scripts carry it (`<script nonce="…">`), the CSP allows them.
	Nonce() string
	// JSON is the body as JSON, at most limit bytes (1 MiB by default): *HttpFailure 400 when malformed, 413 when larger.
	JSON(limit ...int) (any, error)
	// Body is the body's chunks, at most limit bytes (1 MiB by default): *HttpFailure 413 past it, 400 when cut short.
	Body(limit ...int) iter.Seq2[[]byte, error]
}

HttpRequest is a request as routes see it, once admitted: `Origin` and `Provenance` come only from admission.

type HttpResponse

type HttpResponse struct {
	Kind    ResponseKind
	Headers []ResponseHeader
	// Status is the status of json, html, redirect (302, 303 or 307) and error; 0 is the default (200, 302).
	Status int
	// Value is the JSON value of a json response.
	Value any
	// Body is the text of an html response.
	Body string
	// Mime is the type of a bytes response.
	Mime string
	// Size is the length of a bytes response: `Content-Length` and ranges; nil: read until `Read` returns an empty chunk.
	Size *int64
	// Read is `length` bytes from `offset` (fewer only at the end of a body without Size), in the request's scope.
	Read func(offset int64, length int, ctx host.Ctx) ([]byte, error)
	// Download is the file name a bytes response is saved under.
	Download string
	// Inline is shown in the browser instead of saved (an image, a video), with a `sandbox` CSP.
	Inline bool
	// Ranges is whether a single range is answered 206 (with Size).
	Ranges bool
	// To is the target of a redirect.
	To string
	// Message is an error response's text; nil: the status's reason phrase.
	Message *string
}

HttpResponse is a route's answer, as a description; Headers replace same-named default ones (a route widens its own CSP); a list sends one line per value.

func FileResponse

func FileResponse(given string, options FileResponseOptions) (HttpResponse, error)

FileResponse is the file at given as a `bytes` response; *HttpFailure 404 for a missing one (anyone may ask for one: no failure of the route), 403 for one outside Root; it returns what else stat returns.

type HttpRoute

type HttpRoute func(request HttpRequest, ctx host.Ctx) (HttpResponse, error)

HttpRoute answers a request with a response description, in the request's scope (`ctx.Principal()`, its Done).

type HttpRouteEntry

type HttpRouteEntry struct {
	Key   string
	Route HttpRouteOptions
}

HttpRouteEntry is one route of a contribution by its `"METHOD /pattern"`.

func RouteFunc

func RouteFunc(key string, handler HttpRoute) HttpRouteEntry

RouteFunc is a route of a contribution without options.

type HttpRouteOptions

type HttpRouteOptions struct {
	Handler   HttpRoute
	Page      bool
	CrossSite bool
}

HttpRouteOptions is a route with its options: Page admits a top-level navigation from another site (a link to it) with its authentication; CrossSite admits any foreign request (a webhook), always anonymous.

type HttpSocket

type HttpSocket struct {
	Handle func(socket *WebSocketHandle, request HttpRequest, ctx host.Ctx) error
}

HttpSocket is a plugin socket's handler (D6): a WebSocket after the checks and authentication, its `error` listener attached; its scope lasts until the socket closes. Frames are read while Handle runs (pings, pongs and the peer's close are served); the messages that arrive meanwhile are delivered to its OnMessage listeners, in order, when it returned.

type HttpSocketEntry

type HttpSocketEntry struct {
	Pattern string
	Handler *HttpSocket
}

HttpSocketEntry is a plugin socket by pattern (no method).

type HttpWrap

type HttpWrap struct {
	Name  string
	Phase WrapPhase
	// Scope is "own" (default, also ""): around the contributing plugin's routes; "all": every route.
	Scope string
	// Route is only around this route (`"GET /notes/:id"`), "" for none; a route nobody contributes is a reported conflict.
	Route string
	Wrap  func(request HttpRequest, next func(HttpRequest) (HttpResponse, error), ctx host.Ctx) (HttpResponse, error)
}

HttpWrap is a wrap (D2): runs around routes in its phase, around its own plugin's routes unless Scope is "all".

type Incoming

type Incoming interface {
	Method() string
	// URL is the URL as the URL parser serializes it (dot segments resolved, `\` as `/`).
	URL() string
	// Header is a header's value, several of one name joined with ", "; false without it.
	Header(name string) (string, bool)
	// Forwarded is whether a proxy forwarded it: a `Forwarded` or `X-Forwarded-*` header.
	Forwarded() bool
	// Cancelled calls abort once when the client goes away before its answer is written (at once when it has).
	Cancelled(abort func(reason error))
	// Request is the request itself.
	Request() *nethttp.Request
}

Incoming is a request as the component reads it.

func WebIncoming

func WebIncoming(request *nethttp.Request) Incoming

WebIncoming is request as the component reads it.

type LinkOptions

type LinkOptions struct {
	Limits     link.PartLimits
	MaxPayload int
}

LinkOptions is what the links endpoint gives one socket: its parts' limits and its largest frame (1 MiB by default, 0).

type LinksOptions

type LinksOptions struct {
	Path string
	// Options is given to every socket unless OptionsFunc is set.
	Options LinkOptions
	// OptionsFunc is per request and principal; an error is reported `hook_failed` and refuses the upgrade (403).
	OptionsFunc func(request HttpRequest, principal data.Principal) (LinkOptions, error)
}

LinksOptions is the links endpoint's path and what it gives each socket (`maxPayload` 1 MiB by default).

type ListenAddress

type ListenAddress struct {
	Host string
	Port int
}

ListenAddress is where a listener listens.

type Lookup

type Lookup int

Lookup is what a route or socket lookup found.

const (
	// Found: a match.
	Found Lookup = iota
	// NoMatch: no route or socket (Pi's `undefined`).
	NoMatch
	// BadPath: a malformed path (Pi's `"bad_path"`).
	BadPath
)

type Message

type Message struct {
	Data   []byte
	Binary bool
}

Message is a data frame: its payload and whether it was a binary frame (else text, UTF-8).

func (Message) Text

func (m Message) Text() string

Text is the payload as text.

type NodeListener

type NodeListener struct {
	Address ListenAddress
	// contains filtered or unexported fields
}

NodeListener is the listener's native value: a listening server.

func ListenNode

func ListenNode(handler Handler, listen ListenAddress, ctx context.Context) (*NodeListener, error)

ListenNode is a server for handler listening at listen; it returns the listen error (a port in use).

func (*NodeListener) Closed

func (l *NodeListener) Closed()

Closed closes every connection still open and returns once the server closed.

func (*NodeListener) Stop

func (l *NodeListener) Stop()

Stop stops accepting connections and closes the idle ones (the component's close runs next).

type NodeRequest

type NodeRequest struct {
	// Refused is set when the request is refused at the wire.
	Refused *WireRefusal
	// Request is the request to give `Fetch`, with Connection.
	Request    *nethttp.Request
	Connection Connection
}

NodeRequest is a request as an app mounting `Fetch` on its own server gets it: a request, or refused.

func NodeRequestOf

func NodeRequestOf(r *nethttp.Request) NodeRequest

NodeRequestOf converts r for `Fetch` on an app's own server, the whole conversion being the wire boundary: what the listener refuses is refused with the same status (nodeIncomingOf), never a panic. The request's `Host` is in its headers and its URL is the serialized target.

type Nonces

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

Nonces are fresh script nonces, one per response: 16 random bytes each, base64, cut from a pool filled 4 KiB at a time.

func NewNonces

func NewNonces() *Nonces

NewNonces is a nonce source.

func (*Nonces) Next

func (n *Nonces) Next() string

Next is the next nonce (never one handed out before).

type Provenance

type Provenance struct {
	Kind   ProvenanceKind
	Host   string
	Relay  string
	Origin string
}

Provenance is where an admitted request came from: Host for a remote one, Relay and Origin for a relayed one.

type ProvenanceKind

type ProvenanceKind string

ProvenanceKind tells where an admitted request came from.

const (
	ProvenanceLocal   ProvenanceKind = "local"
	ProvenanceRemote  ProvenanceKind = "remote"
	ProvenanceRelayed ProvenanceKind = "relayed"
)

type PulledBody

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

PulledBody is the body of a `bytes` response from `start`, `length` bytes (nil: until an empty read), read one piece per Read, so the consumer's backpressure paces the reads; a `read` that fails or comes back short fails it. It follows the request's scope: once sealed (a disconnect, `close`) the stream errors, no read starts, a late one is dropped.

func (*PulledBody) Close

func (b *PulledBody) Close() error

Close cancels the stream.

func (*PulledBody) Closed

func (b *PulledBody) Closed() <-chan struct{}

Closed is closed once the stream ended: read to its end, failed, cancelled or errored by the scope's seal.

func (*PulledBody) Read

func (b *PulledBody) Read(p []byte) (int, error)

Read pulls the next piece when the last one is taken.

type QueryPair

type QueryPair struct{ Name, Value string }

QueryPair is one name and value of a query.

type Refused

type Refused struct {
	Failed *RelayFailure
}

Refused is what admission refuses, and the relay hook that threw (reported by the caller).

type RelayFailure

type RelayFailure struct {
	Relay string
	Error error
}

RelayFailure is a relay hook that threw (or lied).

type RelayVerified

type RelayVerified struct {
	Origin string
	Framer *string
}

RelayVerified is what a relay says of a request it recognizes; Framer nil for none.

type ResolvedWrap

type ResolvedWrap struct {
	Wrap   *HttpWrap
	Plugin string
}

ResolvedWrap is a wrap as a route runs it, with its plugin.

type ResponseFailure

type ResponseFailure struct {
	Message string
	Cause   error
}

ResponseFailure is a `bytes` body that could not be read whole (a failing or a short `read`).

func (*ResponseFailure) Error

func (e *ResponseFailure) Error() string

func (*ResponseFailure) Unwrap

func (e *ResponseFailure) Unwrap() error

type ResponseHeader

type ResponseHeader struct {
	Name   string
	Values []string
}

ResponseHeader is one header of a response: a list sends one line per value (several `Set-Cookie`).

func HeaderOf

func HeaderOf(name string, values ...string) ResponseHeader

HeaderOf is a response header of one or more values.

type ResponseKind

type ResponseKind string

ResponseKind tells what an HttpResponse describes.

const (
	KindJSON     ResponseKind = "json"
	KindHTML     ResponseKind = "html"
	KindBytes    ResponseKind = "bytes"
	KindRedirect ResponseKind = "redirect"
	KindError    ResponseKind = "error"
)

type RouteMatch

type RouteMatch struct {
	Pattern   string
	Plugin    string
	Params    map[string]string
	Handler   HttpRoute
	Page      bool
	CrossSite bool
	Wraps     []ResolvedWrap
}

RouteMatch is a matched route: its pattern, plugin, params, handler, options and wraps (outermost first).

type Router

type Router struct {

	// Hosts are the hosts contributions allow (lowercased).
	Hosts *StringSet
	// Framers are the origins allowed to frame pages.
	Framers *StringSet
	// Relays are the relays, in contributor order.
	Relays []*HttpRelay
	// Csp is the extra CSP sources by directive.
	Csp []CspEntry
	// SocketHandlers are the socket handlers it serves: a socket handed out by one no longer here is closed.
	SocketHandlers map[*HttpSocket]struct{}
	// contains filtered or unexported fields
}

Router is the router a request uses: as it was when the request started.

func ComposeRouter

ComposeRouter builds the router from table (the registry's `compose`): pure, conflicts reported, the first by plugin name wins.

func (*Router) Route

func (r *Router) Route(method, path string) (*RouteMatch, Lookup)

Route is the route for method and path, with its params and wraps; BadPath for a malformed one.

func (*Router) Socket

func (r *Router) Socket(path string) (*SocketMatch, Lookup)

Socket is the plugin socket for path.

type SameSite

type SameSite uint8

SameSite is a cookie's `SameSite` attribute: Pi's closed union `"Strict" | "Lax"`, which no text can extend.

const (
	// SameSiteStrict is the default.
	SameSiteStrict SameSite = iota
	// SameSiteLax lets a top-level navigation from another site carry the cookie.
	SameSiteLax
)

func (SameSite) String

func (s SameSite) String() string

type Served

type Served struct {
	Answer   Answer
	Finished func()
}

Served is an answer and what its consumer calls once the body is written or abandoned (the request's scope then ends).

type SocketFailure

type SocketFailure struct {
	Pattern string
	Plugin  string
	Error   error
}

SocketFailure is a plugin socket's handler failed: reported, the socket closed (1011).

type SocketMatch

type SocketMatch struct {
	Pattern    string
	Plugin     string
	Params     map[string]string
	Handler    *HttpSocket
	MaxPayload int
}

SocketMatch is a matched plugin socket.

type StringSet

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

StringSet is a set of strings in insertion order (a JavaScript `Set<string>`).

func NewStringSet

func NewStringSet(values ...string) *StringSet

NewStringSet is a set of values.

func (*StringSet) Add

func (s *StringSet) Add(value string)

Add adds value.

func (*StringSet) Has

func (s *StringSet) Has(value string) bool

Has is whether value is in the set.

func (*StringSet) Size

func (s *StringSet) Size() int

Size is how many values the set holds.

func (*StringSet) Values

func (s *StringSet) Values() []string

Values are its values in insertion order.

type URLSearchParams

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

URLSearchParams is the query of a request as `URLSearchParams` reads it (the WHATWG application/x-www-form-urlencoded parser): its pairs in order, `+` a space, percent escapes decoded leniently (a bad one stays as written, bytes that are no UTF-8 become U+FFFD), a `;` just a character. Go's url.ParseQuery drops a pair with a `;` or a bad escape and loses the order, so it is not used. Go-only file.

func ParseURLSearchParams

func ParseURLSearchParams(query string) *URLSearchParams

ParseURLSearchParams is `new URLSearchParams(query)` (the query without its `?`).

func (*URLSearchParams) Get

func (p *URLSearchParams) Get(name string) (string, bool)

Get is the first value of name; false without one.

func (*URLSearchParams) GetAll

func (p *URLSearchParams) GetAll(name string) []string

GetAll is every value of name, in order.

func (*URLSearchParams) Has

func (p *URLSearchParams) Has(name string) bool

Has is whether name has a value.

func (*URLSearchParams) Pairs

func (p *URLSearchParams) Pairs() []QueryPair

Pairs is every pair, in order.

type UpgradeAdmission

type UpgradeAdmission struct {
	// Allowed is the allowed host, "" for none.
	Allowed   string
	Relay     *HttpRelay
	Principal data.Principal
}

UpgradeAdmission is what admitted an upgrade: the allowed host or the relay it came through (local: neither), and its principal.

type Upgrades

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

Upgrades are the upgraded connections of one HTTP component.

func NewUpgrades

func NewUpgrades() *Upgrades

NewUpgrades is an empty set of connections.

func (*Upgrades) Close

func (u *Upgrades) Close(deadline <-chan struct{})

Close closes every connection (1001, "going away"); those still open when deadline is closed are terminated. Upgrades reserved before it are waited for (a handshake takes no time) and closed with the rest; later ones are refused.

func (u *Upgrades) Link(w nethttp.ResponseWriter, request *nethttp.Request, admission UpgradeAdmission, options LinkOptions, h host.Host, ctx context.Context, checked *Router)

Link upgrades request to the links endpoint: `host.accept` over the socket (its output capped) as the admitted principal, with options' limits; ctx is the parent of the work on the link. checked is the router the check read.

func (*Upgrades) Socket

func (u *Upgrades) Socket(w nethttp.ResponseWriter, r *nethttp.Request, admission UpgradeAdmission, match *SocketMatch, request HttpRequest, h host.Host, ctx context.Context, failed func(SocketFailure), checked *Router)

Socket upgrades request to the plugin socket match: its handler gets the socket and request in a `host.root` scope acting as the admitted principal that lasts until the socket closes; a handler that fails is reported and closes it (1011). checked is the router the check read.

type WebSocket

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

WebSocket is an upgraded connection.

func (*WebSocket) BufferedAmount

func (s *WebSocket) BufferedAmount() int64

BufferedAmount is the bytes `Send` queued that have not been written.

func (*WebSocket) Close

func (s *WebSocket) Close(code int, reason string)

Close starts the close handshake with code and reason (no code: code 0), after what is queued; the connection is terminated if the peer does not answer within 30 s.

func (*WebSocket) OnClose

func (s *WebSocket) OnClose(fn func(CloseEvent)) (remove func())

OnClose attaches a listener for the close of the socket (once) and returns its removal.

func (*WebSocket) OnError

func (s *WebSocket) OnError(fn func(error)) (remove func())

OnError attaches a listener for errors of the socket (a frame above the largest payload) and returns its removal.

func (*WebSocket) OnMessage

func (s *WebSocket) OnMessage(fn func(Message)) (remove func())

OnMessage attaches a listener for data frames and returns its removal.

func (*WebSocket) OnPing

func (s *WebSocket) OnPing(fn func(payload []byte)) (remove func())

OnPing attaches a listener for ping frames (answered by the socket itself) and returns its removal.

func (*WebSocket) OnPong

func (s *WebSocket) OnPong(fn func(payload []byte)) (remove func())

OnPong attaches a listener for pong frames and returns its removal.

func (*WebSocket) OnceClose

func (s *WebSocket) OnceClose(fn func(CloseEvent)) (remove func())

OnceClose is OnClose for the first close only.

func (*WebSocket) OncePing

func (s *WebSocket) OncePing(fn func(payload []byte)) (remove func())

OncePing is OnPing for the first ping only.

func (*WebSocket) Ping

func (s *WebSocket) Ping()

Ping sends a ping frame.

func (*WebSocket) ReadyState

func (s *WebSocket) ReadyState() int

ReadyState is 1 open, 2 closing, 3 closed.

func (*WebSocket) Send

func (s *WebSocket) Send(data []byte, binary bool, done func(error))

Send queues a frame (binary or text); done gets the write's error (nil when written). It reports an error when the socket is not open.

func (*WebSocket) Start

func (s *WebSocket) Start()

Start begins reading frames.

func (*WebSocket) Terminate

func (s *WebSocket) Terminate()

Terminate closes the connection at once, no close handshake.

type WebSocketHandle

type WebSocketHandle = WebSocket

WebSocketHandle is Pi's `WebSocketHandle`: the socket a plugin's handler gets.

type WireRefusal

type WireRefusal struct{ Status int }

WireRefusal is what refuses a request at the wire, with its status (400, 403 or 501).

type WrapPhase

type WrapPhase string

WrapPhase is a wrap's phase, outermost first.

const (
	PhaseObserve   WrapPhase = "observe"
	PhaseHeaders   WrapPhase = "headers"
	PhaseTransform WrapPhase = "transform"
)

Jump to

Keyboard shortcuts

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