Documentation
¶
Overview ¶
Package ypy is the official YPY SDK for Go servers.
YPY is a hypermedia framework: the browser sends requests from HTML attributes and the server answers with HTML fragments, signal patches or an event stream. This package is the server side of that conversation, on the standard net/http: handlers are plain http.HandlerFunc values, middleware is func(http.Handler) http.Handler, and nothing is registered globally.
Reading a request ¶
FromRequest reads the YPY headers into a typed Request. Middleware does it once, stores the result in the request context (FromContext) and adds "Vary: YPY-Request" to every response.
Answering ¶
Fragment answers an HTML fragment; Partial adds a <ypy-partial> that goes to its own target. ValidationError (422), SeeOther (303), NoContent and Redirect cover forms. The response headers have one helper each: Location, PushURL, ReplaceURL, Refresh, Reswap, Retarget, Reselect and Trigger with its two variants. The names of all headers are the Header* constants.
Signals ¶
ReadSignals decodes the signals the client sent into a struct, and PatchSignals answers with a JSON Merge Patch (RFC 7396). A Signer signs the read-only signals the server sends (Signer.SignPatch, PatchSignedSignals, Signer.Declaration) and ReadSignedSignals verifies them when they come back, with constant-time comparison and key rotation.
Extensions ¶
The ypy-validate extension marks its field checks with YPY-Validate (Request.Validate, Request.IsValidation); ypy-layers marks the requests of a layer with YPY-Layer (Request.Layer) and a server opens one with OpenLayer; ypy-cache is told what to drop with ExpireCache.
Native app ¶
Inside a native app shell (ADR-0017) Request.Native names the platform and the native components of the installed build, VaryNative keeps caches apart, PathConfig.Handler serves the routes document and NativeNavigate asks the shell to visit a URL.
Streaming ¶
NewStream turns a response into a server-sent event stream with Stream.PatchElements, Stream.PatchSignals, Stream.Redirect, Stream.Event and Stream.Refresh, a keepalive, and a clean end when the client leaves. Broadcaster sends the same events to many clients, with a snapshot for each new connection so a reconnection is safe. The wire format is the protocol specification in spec/PROTOCOL.md of the module's repository.
Model answers ¶
NewModelStream writes the answer of a language model into the page as it is generated: tokens go in through ModelStream.Write, are batched by time and size, and reach the page as closed Markdown blocks plus the open one, with one complete patch at the end. The model's text is untrusted: it goes through a Renderer (the package ypymd has one) and never into a selector or an event name. WithPlainText is the low-cost mode for plain text.
Assets next to templates ¶
"ypy gen assets" extracts the <style ypy-asset> and <script ypy-asset> blocks of the templates into files named by the hash of their content and writes a manifest. LoadManifest reads it; Manifest.Assets writes the <link> and <script> tags with integrity and the page's nonce, and Manifest.Handler serves the files. Nothing is inline, so a strict Content-Security-Policy holds.
Testing ¶
The ypytest package builds requests the way the YPY client sends them and asserts on responses, partials, signals and streams without a browser.
Example (Items) ¶
Wiring is explicit, usually in the application bootstrap.
// SPDX-License-Identifier: MIT
package main
import (
"fmt"
"html"
"net/http"
"net/url"
"strings"
"sync"
ypy "github.com/ypy-develop/go"
"github.com/ypy-develop/go/ypytest"
)
// Items is a small service with explicit wiring: the handler gets what it needs
// in the constructor, there is no container and no global.
type Items struct {
mu sync.Mutex
items []string
}
func (s *Items) add(title string) int {
s.mu.Lock()
defer s.mu.Unlock()
s.items = append(s.items, title)
return len(s.items)
}
// Create answers the form of "add an item", for a YPY request and for a plain
// browser post alike.
func (s *Items) Create(w http.ResponseWriter, r *http.Request) {
title := strings.TrimSpace(r.PostFormValue("title"))
if title == "" {
// 422 with the form and its error: the client swaps it in place.
ypy.ValidationError(w, `<form id="new"><p class="error">Title is required</p></form>`)
return
}
n := s.add(title)
if !ypy.FromRequest(r).IsYPY {
ypy.SeeOther(w, "/items") // a browser without the client: post, redirect, get
return
}
// The row goes to the target of the request; the counter and a toast go to
// their own places, and the page is told with an event.
ypy.Fragment(w, `<li>`+html.EscapeString(title)+`</li>`)
ypy.Partial(w, ypy.PartialSpec{Target: "#count", Swap: "innerHTML"}, fmt.Sprintf("%d items", n))
ypy.Partial(w, ypy.PartialSpec{ID: "toast"}, "<p>Saved</p>")
ypy.Trigger(w, "item:saved", map[string]any{"count": n})
}
// Wiring is explicit, usually in the application bootstrap.
func main() {
items := &Items{}
mux := http.NewServeMux()
mux.HandleFunc("POST /items", items.Create)
handler := ypy.Middleware(mux)
post := func(title string, opts ...ypytest.Option) *ypytest.Response {
opts = append(opts, ypytest.Form(url.Values{"title": {title}}))
return ypytest.Do(handler, ypytest.NewRequest("POST", "/items", opts...))
}
res := post("Buy <milk>")
fmt.Println(res.Status(), res.Header("YPY-Trigger"))
fmt.Println(res.Body())
fmt.Println(post("").Status())
fmt.Println(post("Plain", ypytest.NotYPY()).Status())
}
Output: 200 {"item:saved":{"count":1}} <li>Buy <milk></li><ypy-partial ypy-target="#count" ypy-swap="innerHTML">1 items</ypy-partial><ypy-partial id="toast"><p>Saved</p></ypy-partial> 422 303
Index ¶
- Constants
- Variables
- func AtomicGroup(w http.ResponseWriter)
- func EvictCache(w http.ResponseWriter, patterns ...string) error
- func ExpireCache(w http.ResponseWriter, patterns ...string) error
- func Fragment(w http.ResponseWriter, markup string, opts ...FragmentOption) error
- func FragmentStatus(w http.ResponseWriter, status int, markup string, opts ...FragmentOption) error
- func KeepCache(w http.ResponseWriter)
- func Location(w http.ResponseWriter, loc LocationOptions) error
- func Middleware(next http.Handler) http.Handler
- func NativeMiddleware(next http.Handler) http.Handler
- func NativeNavigate(w http.ResponseWriter, url, action string) error
- func NewMiddleware(opts ...FragmentOption) func(http.Handler) http.Handler
- func NoContent(w http.ResponseWriter)
- func OpenLayer(w http.ResponseWriter, url string, opts ...LayerOptions) error
- func OpenLayerHTML(w http.ResponseWriter, markup string, opts ...LayerOptions) error
- func Partial(w http.ResponseWriter, spec PartialSpec, markup string, opts ...FragmentOption) error
- func PatchSignals(w http.ResponseWriter, patch any) error
- func PatchSignedSignals(w http.ResponseWriter, s *Signer, patch any, names ...string) error
- func PushURL(w http.ResponseWriter, url string)
- func RawSignals(r *http.Request) ([]byte, error)
- func ReadSignals[T any](r *http.Request) (T, error)
- func ReadSignedSignals[T any](r *http.Request, s *Signer, names ...string) (T, error)
- func Redirect(w http.ResponseWriter, r *http.Request, url string)
- func Refresh(w http.ResponseWriter)
- func ReplaceURL(w http.ResponseWriter, url string)
- func Reselect(w http.ResponseWriter, selector string)
- func Reswap(w http.ResponseWriter, swap string)
- func Retarget(w http.ResponseWriter, selector string)
- func SeeOther(w http.ResponseWriter, url string)
- func StreamFunc(fn func(s *Stream, r *http.Request) error, opts ...StreamOption) http.Handler
- func Trigger(w http.ResponseWriter, name string, payload any) error
- func TriggerAfterSettle(w http.ResponseWriter, name string, payload any) error
- func TriggerAfterSwap(w http.ResponseWriter, name string, payload any) error
- func ValidationError(w http.ResponseWriter, markup string, opts ...FragmentOption) error
- func VaryNative(w http.ResponseWriter)
- type Asset
- type BlockRenderer
- type Broadcaster
- func (b *Broadcaster) Close()
- func (b *Broadcaster) Event(name string, detail any, opts ...CustomOption) error
- func (b *Broadcaster) Len() int
- func (b *Broadcaster) PatchElements(markup string, opts ...ElementsOption) error
- func (b *Broadcaster) PatchSignals(patch any, opts ...SignalsOption) error
- func (b *Broadcaster) Publish(ev Event) int
- func (b *Broadcaster) Redirect(url string, opts ...RedirectOption) error
- func (b *Broadcaster) Refresh(opts ...RefreshOption) error
- func (b *Broadcaster) ServeHTTP(w http.ResponseWriter, r *http.Request)
- type BroadcasterOption
- type CSRF
- func (c *CSRF) Check(r *http.Request) error
- func (c *CSRF) Field(r *http.Request) template.HTML
- func (c *CSRF) Meta(r *http.Request) template.HTML
- func (c *CSRF) Middleware(next http.Handler) http.Handler
- func (c *CSRF) Renew(w http.ResponseWriter, r *http.Request)
- func (c *CSRF) RenewFor(w http.ResponseWriter, session string)
- func (c *CSRF) Token(r *http.Request) string
- func (c *CSRF) TokenFor(session string) string
- type CSRFOption
- func CSRFHeaderName(name string) CSRFOption
- func CSRFOnFailure(fn func(w http.ResponseWriter, r *http.Request, err error)) CSRFOption
- func CSRFPreviousKeys(keys ...[]byte) CSRFOption
- func CSRFSecure() CSRFOption
- func CSRFSession(fn func(*http.Request) string) CSRFOption
- func CSRFTrustedOrigins(origins ...string) CSRFOption
- type Context
- type CustomOption
- type ElementsOption
- type Event
- func CustomEvent(name string, detail any, opts ...CustomOption) (Event, error)
- func PatchElementsEvent(markup string, opts ...ElementsOption) (Event, error)
- func PatchSignalsEvent(patch any, opts ...SignalsOption) (Event, error)
- func RedirectEvent(url string, opts ...RedirectOption) (Event, error)
- func RefreshEvent(opts ...RefreshOption) (Event, error)
- type FragmentOption
- type LayerMode
- type LayerOptions
- type LayerSide
- type LocationOptions
- type Manifest
- func (m *Manifest) Assets(origin string, nonce ...string) template.HTML
- func (m *Manifest) FuncMap() template.FuncMap
- func (m *Manifest) Handler() http.Handler
- func (m *Manifest) Integrity(file string) (string, bool)
- func (m *Manifest) Lookup(origin string) (Asset, bool)
- func (m *Manifest) Origins() []string
- func (m *Manifest) WithBase(base string) *Manifest
- type ModalStyle
- type ModelOption
- func WithAnnounce(start, ready, stopped, failed string) ModelOption
- func WithAnswerID(id string) ModelOption
- func WithFailText(s string) ModelOption
- func WithFlushBytes(n int) ModelOption
- func WithFlushInterval(d time.Duration) ModelOption
- func WithFollow() ModelOption
- func WithMaxBytes(n int) ModelOption
- func WithModelTarget(selector string, mode PatchMode) ModelOption
- func WithPlainText() ModelOption
- func WithRenderer(r Renderer) ModelOption
- func WithShortAnswer() ModelOption
- func WithStopText(s string) ModelOption
- type ModelStream
- func (m *ModelStream) Cancel() error
- func (m *ModelStream) Close() error
- func (m *ModelStream) Context() context.Context
- func (m *ModelStream) Fail() error
- func (m *ModelStream) Flush() error
- func (m *ModelStream) ID() string
- func (m *ModelStream) Text() string
- func (m *ModelStream) Write(p []byte) (int, error)
- func (m *ModelStream) WriteString(s string) (int, error)
- type Namespace
- type Native
- type PartialSpec
- type PatchMode
- type PathConfig
- type PathProperties
- type PathRule
- type PathSettings
- type PathTab
- type Presentation
- type QueryString
- type RedirectMode
- type RedirectOption
- type RefreshOption
- type Renderer
- type Request
- type RequestType
- type SignalsOption
- type SignatureError
- type Signer
- func (s *Signer) Bind(binding string) *Signer
- func (s *Signer) Declaration(values any, names ...string) (string, error)
- func (s *Signer) Sign(name string, value any) (string, error)
- func (s *Signer) SignPatch(patch any, names ...string) (map[string]any, error)
- func (s *Signer) Verify(name string, value any, signature string) error
- func (s *Signer) VerifySignals(doc []byte, names ...string) error
- type Stream
- func (s *Stream) Close()
- func (s *Stream) Context() context.Context
- func (s *Stream) Done() <-chan struct{}
- func (s *Stream) Event(name string, detail any, opts ...CustomOption) error
- func (s *Stream) PatchElements(markup string, opts ...ElementsOption) error
- func (s *Stream) PatchSignals(patch any, opts ...SignalsOption) error
- func (s *Stream) Redirect(url string, opts ...RedirectOption) error
- func (s *Stream) Refresh(opts ...RefreshOption) error
- func (s *Stream) Send(ev Event) error
- func (s *Stream) SendBatch(evs ...Event) error
- type StreamOption
Examples ¶
Constants ¶
const ( // CSRFHeader is the default request header that carries the token. The // extension reads another name from the data-header of its meta tag; use // [CSRFHeaderName] to match it. CSRFHeader = "X-CSRF-Token" // CSRFFormField is the form field that carries the token when the request // is a plain form post with no header. CSRFFormField = "csrf_token" // CSRFMetaName is the name of the meta tag that holds the token for the // ypy-csrf extension; [CSRF.Meta] writes it. CSRFMetaName = "ypy-csrf" )
Names of the CSRF protection. The ypy-csrf extension sends the token in CSRFHeader; a plain form post sends it in CSRFFormField. The protocol specification (spec/PROTOCOL.md, "CSRF token") documents them.
const ( // EventPatchElements patches the DOM with HTML. EventPatchElements = "ypy-patch-elements" // EventPatchSignals merges a JSON Merge Patch (RFC 7396) into the signals. EventPatchSignals = "ypy-patch-signals" // EventRedirect navigates the page. EventRedirect = "ypy-redirect" // EventCustom fires a DOM event on the client. EventCustom = "ypy-event" // EventRefresh tells every client to fetch its own page, or one of its // elements, again. EventRefresh = "ypy-refresh" )
The event names of the YPY streaming protocol (spec/PROTOCOL.md).
const ( // HeaderRequest is "true" on every request the YPY client makes. A history // restore request leaves it out on purpose, so a full page answers it. HeaderRequest = "YPY-Request" // HeaderBoosted is "true" when the request comes from a boosted link or form. HeaderBoosted = "YPY-Boosted" // HeaderHistoryRestore is "true" when the request restores a page from the // history after a back or forward navigation. HeaderHistoryRestore = "YPY-History-Restore-Request" // HeaderTarget identifies the element the response is swapped into, as // tag#id (for example div#feed). HeaderTarget = "YPY-Target" // HeaderSource identifies the element that made the request, as tag#id. HeaderSource = "YPY-Source" // HeaderRequestType is "full" when the response replaces the whole page // content and "partial" when it fills a smaller target. HeaderRequestType = "YPY-Request-Type" // HeaderCurrentURL is the URL of the page that made the request. HeaderCurrentURL = "YPY-Current-URL" // HeaderPrompt carries the answer to a prompt the user filled in (the // client sends it URI-encoded). HeaderPrompt = "YPY-Prompt" // HeaderValidate is sent by the ypy-validate extension with the name of the // field being checked (its id when it has no name). A request that carries // it is a check, not the real action: it must change nothing. HeaderValidate = "YPY-Validate" // HeaderLayer is sent by the ypy-layers extension with the kind of layer // ("modal", "drawer" or "popup") that the response fills, or that the // request started in. HeaderLayer = "YPY-Layer" // HeaderNative is sent by the ypy-native extension, inside a native app // shell, on every YPY request: "<platform>; v=<n>; caps=<a,b,c>". The // caps are the native components the installed app build knows. See // [Native] and [Request.Native]. HeaderNative = "YPY-Native" // HeaderRedirect makes the client navigate to a URL with a full page load. HeaderRedirect = "YPY-Redirect" // HeaderLocation makes the client navigate without a full page load. Its // value is a path or a JSON object, see [LocationOptions]. HeaderLocation = "YPY-Location" // HeaderPushURL pushes a URL on the history ("false" prevents the push). HeaderPushURL = "YPY-Push-Url" // HeaderReplaceURL replaces the current history entry ("false" prevents it). HeaderReplaceURL = "YPY-Replace-Url" // HeaderRefresh is "true" to make the client reload the page. HeaderRefresh = "YPY-Refresh" // HeaderReswap overrides the swap style of the response. HeaderReswap = "YPY-Reswap" // HeaderRetarget overrides the target selector of the response. HeaderRetarget = "YPY-Retarget" // HeaderReselect overrides the selector of the content taken from the response. HeaderReselect = "YPY-Reselect" // HeaderTrigger names client events to fire as soon as the response arrives. HeaderTrigger = "YPY-Trigger" // HeaderTriggerAfterSwap names client events to fire after the swap. HeaderTriggerAfterSwap = "YPY-Trigger-After-Swap" // HeaderTriggerAfterSettle names client events to fire after the settle step. HeaderTriggerAfterSettle = "YPY-Trigger-After-Settle" // HeaderOpenLayer makes the ypy-layers extension open a layer instead of // swapping the response. Its value is JSON, or just a URL; see [OpenLayer]. HeaderOpenLayer = "YPY-Open-Layer" // HeaderCSRF carries a new CSRF token on a response: the ypy-csrf extension // puts it in its meta tag and sends it with the next request. See [CSRF.Renew]. HeaderCSRF = "YPY-CSRF" // HeaderCacheExpire tells the ypy-cache extension which cached copies are // stale: they are still shown at once and always revalidated. A comma // separated list of URL patterns or "tag:<name>", or "false"; see // [ExpireCache]. HeaderCacheExpire = "YPY-Cache-Expire" // HeaderCacheEvict tells the ypy-cache extension which cached copies to // remove, in the same format; see [EvictCache]. HeaderCacheEvict = "YPY-Cache-Evict" // HeaderGroup set to "atomic" makes the client apply the swap of the // response all or nothing: when one target of the main swap, an // out-of-band element or a partial is missing, nothing is swapped and the // history is not touched; see [AtomicGroup]. HeaderGroup = "YPY-Group" )
The HTTP header names of the YPY protocol. They are the only place in the module where a header is spelled out: every other file uses these constants.
Request headers are sent by the browser and read with FromRequest; response headers are set by the server with the helpers in this package.
const ( // NativeUserAgentToken is the product token the shell appends to the // user-agent of every request of its web view, as // "YpyNative/<n> (<platform>)". NativeUserAgentToken = "YpyNative" // NativePathConfigPath is the well-known path of the path configuration // document, see [PathConfig.Handler]. NativePathConfigPath = "/.well-known/ypy-native.json" // its detail is {"url", "action"}, see [NativeNavigate]. EventNativeNavigate = "ypy:native:navigate" )
The native app bridge (ADR-0017). A native shell adds a token to the user-agent of its web view, the ypy-native extension adds HeaderNative to every YPY request, and the shell reads the path configuration document.
const ( NavigateAdvance = "advance" NavigateReplace = "replace" NavigateRestore = "restore" )
The navigation actions of NativeNavigate.
const DefaultAssetsBase = "/assets/"
DefaultAssetsBase is the URL prefix Manifest.Assets and Manifest.Handler use until Manifest.WithBase says otherwise.
const DefaultRefreshDebounce = 250 * time.Millisecond
DefaultRefreshDebounce is the window the client waits before it fetches again when a refresh event does not say otherwise.
const HeaderRobotsTag = "X-Robots-Tag"
HeaderRobotsTag is the response header that tells search engines and AI crawlers what they may do with a page. It is not a YPY header: the SDK only uses it to keep fragments out of an index.
const MaxSignalsBytes = 1 << 20
MaxSignalsBytes is the largest signals document ReadSignals accepts from a JSON body.
const MinKeyBytes = 32
MinKeyBytes is the shortest signing key NewSigner accepts.
const RobotsNoIndex = "noindex"
RobotsNoIndex is the value the SDK puts in HeaderRobotsTag on a fragment.
const SignalsParam = "ypy-signals"
SignalsParam is the name of the query parameter (and of the form field) that carries the signals of the client when the request has no JSON body. It is the only place in the module where the name is spelled out; the protocol specification (spec/PROTOCOL.md, "Signals in requests") documents it.
const SignatureSignal = "ypySig"
SignatureSignal is the name of the reserved signal that carries the signatures: an object from the name of a signed signal to its signature. The client cannot start it with an underscore (those never reach the server), so it has none. The protocol specification (spec/PROTOCOL.md, "Signed read-only signals") documents it.
Variables ¶
var ( // ErrCSRFMissing is returned by [CSRF.Check] when an unsafe request carries // no token, neither in the header nor in the form field. ErrCSRFMissing = errors.New("ypy: CSRF token missing") // ErrCSRFInvalid is returned when the token does not belong to the session // of the request: it is wrong, it is from another session, or the session // changed since the page was made. ErrCSRFInvalid = errors.New("ypy: CSRF token invalid") // ErrCSRFOrigin is returned when the browser says the request comes from // another origin (the Origin header, or Sec-Fetch-Site: cross-site). ErrCSRFOrigin = errors.New("ypy: cross-origin request refused") )
var ( // ErrSignatureMissing is the error (inside a [*SignatureError]) of a signed // signal that came back without its signature, or did not come back. ErrSignatureMissing = errors.New("ypy: signature missing") // ErrSignatureInvalid is the error (inside a [*SignatureError]) of a signal // whose signature does not match its value: the value was changed, the // signature is malformed, or it was made with another key or binding. ErrSignatureInvalid = errors.New("ypy: signature does not match") // ErrWeakKey is returned by [NewSigner] for a key shorter than [MinKeyBytes]. ErrWeakKey = errors.New("ypy: signing key too short") )
var ErrModelDone = errors.New("ypy: model stream finished")
ErrModelDone is returned by a ModelStream write after the answer has ended (closed, stopped, failed or over its byte cap). A provider loop that sees it should stop reading.
var ErrModelLimit = errors.New("ypy: model answer is over its byte cap")
ErrModelLimit is returned by the write that passes the byte cap of WithMaxBytes. The answer ends as a stop, with the stop text of the application.
var ErrNoSignals = errors.New("ypy: request carries no signals")
ErrNoSignals is returned by ReadSignals and RawSignals when the request carries no signals.
var ErrSignalsTooLarge = errors.New("ypy: signals document too large")
ErrSignalsTooLarge is returned when a JSON body is over MaxSignalsBytes.
var ErrStreamClosed = errors.New("ypy: stream closed")
ErrStreamClosed is returned by a Stream write after Close.
Functions ¶
func AtomicGroup ¶
func AtomicGroup(w http.ResponseWriter)
AtomicGroup sets YPY-Group: atomic, so the client applies the swap of this response all or nothing (see HeaderGroup).
func EvictCache ¶
func EvictCache(w http.ResponseWriter, patterns ...string) error
EvictCache tells the ypy-cache extension to remove the cached copies the patterns name (same patterns as ExpireCache). A request that is not a GET and succeeds already removes every copy when the response has neither header, so the helpers are for narrowing that down (see KeepCache) and for GET responses that change what others show.
func ExpireCache ¶
func ExpireCache(w http.ResponseWriter, patterns ...string) error
ExpireCache tells the ypy-cache extension that the cached copies whose path matches any of the patterns are stale: they are still shown at once, and always revalidated with the server. A pattern is "/reports" (that path, with any query), "/reports*" (everything that starts with it), "*" (every copy) or "tag:<name>" (the copies of elements with that ypy-cache-tags name). Put it on the response the page receives: when a handler answers 303, the client only sees the headers of the final response. Calling it again adds patterns. Use EvictCache to remove copies instead.
It returns an error, and sets nothing, when a pattern is empty, has a comma, space, control character or non-ASCII byte, or is "false".
func Fragment ¶
func Fragment(w http.ResponseWriter, markup string, opts ...FragmentOption) error
Fragment answers 200 with markup as an HTML fragment. The markup is written as it is: escape user data when you build it (html/template does).
A fragment is a piece of a page, so the response also carries "X-Robots-Tag: noindex" and "Vary: YPY-Request": a search engine or an AI crawler that reaches it does not index it, and a cache keeps it apart from the page. A markup that is a whole document (it starts with a doctype or an html element) gets no noindex. Pass AllowIndex to leave the header out of a fragment that may be indexed; a value already set in X-Robots-Tag is kept.
Example ¶
package main
import (
"fmt"
"net/http/httptest"
ypy "github.com/ypy-develop/go"
)
func main() {
rec := httptest.NewRecorder()
ypy.Fragment(rec, `<li class="item">New item</li>`)
fmt.Println(rec.Code, rec.Header().Get("Content-Type"))
fmt.Println(rec.Body.String())
}
Output: 200 text/html; charset=utf-8 <li class="item">New item</li>
func FragmentStatus ¶
func FragmentStatus(w http.ResponseWriter, status int, markup string, opts ...FragmentOption) error
FragmentStatus answers an HTML fragment with the given status. It sets the headers described at Fragment.
func KeepCache ¶
func KeepCache(w http.ResponseWriter)
KeepCache sets YPY-Cache-Expire to "false": no copy is expired or removed, and the default of a successful non-GET request (remove every copy) is turned off.
func Location ¶
func Location(w http.ResponseWriter, loc LocationOptions) error
Location sets YPY-Location. With only Path set the header is the plain path; otherwise it is a JSON object. It returns an error when Path is empty or the values cannot be encoded.
Example ¶
package main
import (
"fmt"
"net/http/httptest"
ypy "github.com/ypy-develop/go"
)
func main() {
rec := httptest.NewRecorder()
ypy.Location(rec, ypy.LocationOptions{Path: "/inbox", Target: "#main", Swap: "innerMorph"})
fmt.Println(rec.Header().Get("YPY-Location"))
}
Output: {"path":"/inbox","target":"#main","swap":"innerMorph"}
func Middleware ¶
Middleware reads the YPY headers once, puts the result in the request context (read it back with FromContext) and adds "Vary: YPY-Request" to every response, so a cache never serves a fragment to a page load or the other way round. It also adds "X-Robots-Tag: noindex" to the answer of a YPY request that expects a fragment, so a crawler does not index a piece of a page; NewMiddleware with AllowIndex turns that off. It has the standard net/http middleware shape, so it fits a chain such as the one of the Arandu framework.
Example ¶
package main
import (
"fmt"
"net/http"
ypy "github.com/ypy-develop/go"
"github.com/ypy-develop/go/ypytest"
)
func main() {
handler := ypy.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ypy.FromContext(r.Context()).IsPartial() {
ypy.Fragment(w, "<li>a fragment</li>")
return
}
fmt.Fprint(w, "<html><body><li>a page</li></body></html>")
}))
for _, opts := range [][]ypytest.Option{{ypytest.NotYPY()}, {}} {
res := ypytest.Do(handler, ypytest.NewRequest("GET", "/", opts...))
fmt.Println(res.Body(), "| Vary:", res.Header("Vary"))
}
}
Output: <html><body><li>a page</li></body></html> | Vary: YPY-Request <li>a fragment</li> | Vary: YPY-Request
func NativeMiddleware ¶
NativeMiddleware calls VaryNative on every response. It is separate from Middleware so a server that never varies on the app does not pay the cache cost; it fits in a chain next to it.
func NativeNavigate ¶
func NativeNavigate(w http.ResponseWriter, url, action string) error
NativeNavigate asks the app shell to visit url, with HeaderTrigger and the client event EventNativeNavigate ({"url", "action"}). The shell applies the path configuration of the destination. action is NavigateAdvance, NavigateReplace or NavigateRestore; empty means advance. Outside an app the event has no listener and nothing happens, so send it only to a request for which Request.IsNative is true. It returns an error, and sets nothing, for an empty url, one with a control character, or an unknown action.
func NewMiddleware ¶
func NewMiddleware(opts ...FragmentOption) func(http.Handler) http.Handler
NewMiddleware is Middleware with options. Besides "Vary: YPY-Request" on every response, it adds "X-Robots-Tag: noindex" to the answer of a YPY request that expects a fragment (see Request.IsPartial), so a crawler that reaches a fragment through a cache or a leaked link does not index a piece of a page. A handler that sets X-Robots-Tag itself keeps its value. Pass AllowIndex to leave the header out.
func NoContent ¶
func NoContent(w http.ResponseWriter)
NoContent answers 204 with no body: the request worked and nothing changes on the page.
func OpenLayer ¶
func OpenLayer(w http.ResponseWriter, url string, opts ...LayerOptions) error
OpenLayer asks the client to open a layer that loads url, instead of swapping the response. The header is the bare URL when no options are given and the URL is plain ASCII, and a JSON object otherwise; the JSON is always ASCII, as a header must be. Only the header is set: the status and the body are up to the handler (usually NoContent).
It returns an error, and sets nothing, when url is empty or has a control character, or when an option is not one the client knows (a mode that is not modal, drawer or popup, a side that is not start, end, top or bottom, an empty event name).
func OpenLayerHTML ¶
func OpenLayerHTML(w http.ResponseWriter, markup string, opts ...LayerOptions) error
OpenLayerHTML is like OpenLayer for a layer that shows markup the server already has, with no request. The markup travels in the header, so keep it small; for anything larger give the layer a URL.
func Partial ¶
func Partial(w http.ResponseWriter, spec PartialSpec, markup string, opts ...FragmentOption) error
Partial writes one <ypy-partial> to the response. A response can hold many: call Partial once per target, after Fragment if the response also has main content (the client swaps the main content first, then the partials). It sets the HTML content type when none is set, and writes no status. When it is the first write of the response it also sets the headers described at Fragment.
Example ¶
package main
import (
"fmt"
"net/http/httptest"
ypy "github.com/ypy-develop/go"
)
func main() {
rec := httptest.NewRecorder()
ypy.Fragment(rec, `<li>New item</li>`)
ypy.Partial(rec, ypy.PartialSpec{Target: "#count", Swap: "innerHTML"}, `<b>12</b> items`)
ypy.Partial(rec, ypy.PartialSpec{ID: "toast"}, `<p>Saved</p>`)
fmt.Println(rec.Body.String())
}
Output: <li>New item</li><ypy-partial ypy-target="#count" ypy-swap="innerHTML"><b>12</b> items</ypy-partial><ypy-partial id="toast"><p>Saved</p></ypy-partial>
func PatchSignals ¶
func PatchSignals(w http.ResponseWriter, patch any) error
PatchSignals answers with a signals patch as application/json, which the client merges into its signals (JSON Merge Patch, RFC 7396: null deletes a key). patch is encoded with encoding/json, except a json.RawMessage, which is used as it is and must be a valid JSON object.
Example ¶
package main
import (
"fmt"
"net/http/httptest"
ypy "github.com/ypy-develop/go"
)
func main() {
rec := httptest.NewRecorder()
ypy.PatchSignals(rec, map[string]any{"page": 3, "draft": nil}) // null deletes "draft"
fmt.Println(rec.Header().Get("Content-Type"), rec.Body.String())
}
Output: application/json {"draft":null,"page":3}
func PatchSignedSignals ¶
PatchSignedSignals is PatchSignals with the signatures of Signer.SignPatch.
func PushURL ¶
func PushURL(w http.ResponseWriter, url string)
PushURL pushes url on the browser history. "false" tells the client not to push the URL it would push anyway.
func RawSignals ¶
RawSignals returns the JSON document of the signals the client sent. It looks in three places, in this order:
- the SignalsParam query parameter (what the client uses on GET);
- the body, when the content type is JSON (the whole body is the document);
- the SignalsParam form field of a form post.
A JSON body is put back, so the handler can read it again. It returns ErrNoSignals when there is none.
func ReadSignals ¶
ReadSignals decodes the signals the client sent into T, usually a struct with json tags. Unknown keys are ignored, as encoding/json does. It returns ErrNoSignals (with the zero T) when the request has none, so a handler can tell "no signals" from "empty signals".
Example ¶
package main
import (
"fmt"
ypy "github.com/ypy-develop/go"
"github.com/ypy-develop/go/ypytest"
)
func main() {
type Search struct {
Query string `json:"query"`
Page int `json:"page"`
}
r := ypytest.NewRequest("POST", "/search", ypytest.Signals(Search{Query: "go", Page: 2}))
s, err := ypy.ReadSignals[Search](r)
fmt.Println(s.Query, s.Page, err)
}
Output: go 2 <nil>
Example (Form) ¶
package main
import (
"fmt"
"net/url"
ypy "github.com/ypy-develop/go"
"github.com/ypy-develop/go/ypytest"
)
func main() {
// A form post can carry the signals in a form field.
r := ypytest.NewRequest("POST", "/", ypytest.Form(url.Values{ypy.SignalsParam: {`{"name":"Ana"}`}}))
m, _ := ypy.ReadSignals[map[string]string](r)
fmt.Println(m["name"])
}
Output: Ana
func ReadSignedSignals ¶
ReadSignedSignals is ReadSignals for a request whose signals include server-owned ones: it verifies the signatures of names with s before it decodes anything, so a handler never sees a value the server did not sign. It returns ErrNoSignals when the request has none, and the errors of Signer.VerifySignals. T may leave SignatureSignal out: unknown keys are ignored.
func Redirect ¶
func Redirect(w http.ResponseWriter, r *http.Request, url string)
Redirect sends the client to url. A YPY request gets the YPY-Redirect header and 204 with no body (a body would be swapped in before the navigation); any other request gets 303 See Other, which makes the browser turn a POST into a GET at the new address.
Example ¶
package main
import (
"fmt"
"net/http"
ypy "github.com/ypy-develop/go"
"github.com/ypy-develop/go/ypytest"
)
func main() {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ypy.Redirect(w, r, "/items/7")
})
res := ypytest.Do(handler, ypytest.NewRequest("POST", "/items"))
fmt.Println(res.Status(), res.Header("YPY-Redirect"))
res = ypytest.Do(handler, ypytest.NewRequest("POST", "/items", ypytest.NotYPY()))
fmt.Println(res.Status(), res.Header("Location"))
}
Output: 204 /items/7 303 /items/7
func Refresh ¶
func Refresh(w http.ResponseWriter)
Refresh makes the client reload the current page.
func ReplaceURL ¶
func ReplaceURL(w http.ResponseWriter, url string)
ReplaceURL replaces the current history entry with url. "false" prevents a replacement the client would make anyway.
func Reselect ¶
func Reselect(w http.ResponseWriter, selector string)
Reselect overrides which part of the response is swapped in.
func Reswap ¶
func Reswap(w http.ResponseWriter, swap string)
Reswap overrides the swap style of the response (for example "innerHTML").
func Retarget ¶
func Retarget(w http.ResponseWriter, selector string)
Retarget overrides the target of the response with a selector.
func SeeOther ¶
func SeeOther(w http.ResponseWriter, url string)
SeeOther answers a form that succeeded: 303 See Other with a Location header and no body, so the browser follows it with a GET and a reload never posts the form again. For a redirect that also covers YPY requests, see Redirect.
func StreamFunc ¶
StreamFunc adapts a function to an http.Handler that opens a Stream, runs fn and closes the stream when fn returns, whatever it returns: a send error means the client is gone, and the response is already committed, so there is nothing else to answer. If the stream cannot start the handler answers 500.
Example ¶
package main
import (
"fmt"
"net/http"
ypy "github.com/ypy-develop/go"
"github.com/ypy-develop/go/ypytest"
)
func main() {
handler := ypy.StreamFunc(func(s *ypy.Stream, r *http.Request) error {
return s.PatchElements(`<p id="clock">12:00</p>`)
})
res := ypytest.Do(handler, ypytest.NewRequest("GET", "/clock"))
fmt.Println(res.Header("Content-Type"), len(res.Events()))
}
Output: text/event-stream 1
func Trigger ¶
func Trigger(w http.ResponseWriter, name string, payload any) error
Trigger asks the client to fire the event name as soon as the response arrives. The payload becomes the event detail: an object is sent as it is, any other value is wrapped by the client as {"value": payload}, and nil sends an empty detail. Calling Trigger again adds more events to the same header.
Example ¶
package main
import (
"fmt"
"net/http/httptest"
ypy "github.com/ypy-develop/go"
)
func main() {
rec := httptest.NewRecorder()
ypy.Trigger(rec, "item:saved", map[string]any{"id": 7})
ypy.Trigger(rec, "refresh", nil)
fmt.Println(rec.Header().Get("YPY-Trigger"))
}
Output: {"item:saved":{"id":7},"refresh":{}}
func TriggerAfterSettle ¶
func TriggerAfterSettle(w http.ResponseWriter, name string, payload any) error
TriggerAfterSettle is like Trigger, fired after the settle step.
func TriggerAfterSwap ¶
func TriggerAfterSwap(w http.ResponseWriter, name string, payload any) error
TriggerAfterSwap is like Trigger, fired after the swap.
func ValidationError ¶
func ValidationError(w http.ResponseWriter, markup string, opts ...FragmentOption) error
ValidationError answers a form that did not validate: 422 Unprocessable Content with markup (the form with its errors) as the body. The client swaps 4xx answers of this kind in, so the user sees the errors in place. It sets the headers described at Fragment.
Example ¶
package main
import (
"fmt"
"net/http/httptest"
ypy "github.com/ypy-develop/go"
)
func main() {
rec := httptest.NewRecorder()
ypy.ValidationError(rec, `<form><p class="error">Name is required</p></form>`)
fmt.Println(rec.Code)
}
Output: 422
func VaryNative ¶
func VaryNative(w http.ResponseWriter)
VaryNative adds "Vary: YPY-Native, User-Agent" to the response. Call it on every answer whose HTML depends on Request.Native (the header is the signal of a YPY request, the user-agent suffix the signal of the first load), so a cache keeps the app's page apart from the browser's.
Types ¶
type Asset ¶
Asset is the pair of files one origin of the manifest has. A file is a path relative to the manifest; either may be empty.
type BlockRenderer ¶
type BlockRenderer interface {
Renderer
Blocks(text string) (closed string, consumed int, open string, err error)
}
BlockRenderer is a Renderer that can also split a text into the blocks that are closed and the one still being written. ModelStream uses it to append each closed block once and to replace only the open block at every flush. consumed is how many bytes of text the closed blocks take. The closed blocks followed by the open one must equal Render of the whole text. A Renderer that is not a BlockRenderer is called with the whole text at every flush.
type Broadcaster ¶
type Broadcaster struct {
// contains filtered or unexported fields
}
Broadcaster sends the same events to many connected clients. Mount it as the handler of the stream route; call Publish (or the typed helpers) from anywhere. It is safe for concurrent use.
Publishing never blocks on a client: each client has a bounded queue, and a client that cannot keep up is dropped. It reconnects on its own and receives the snapshot again.
Example ¶
package main
import (
"bufio"
"fmt"
"net/http"
"net/http/httptest"
"strings"
ypy "github.com/ypy-develop/go"
)
func main() {
room := ypy.NewBroadcaster(ypy.WithSnapshot(func(r *http.Request) ([]ypy.Event, error) {
ev, err := ypy.PatchElementsEvent(`<ul id="messages"></ul>`)
return []ypy.Event{ev}, err
}))
defer room.Close()
srv := httptest.NewServer(room) // in an application: mux.Handle("GET /room/events", room)
defer srv.Close()
resp, err := http.Get(srv.URL)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
lines := bufio.NewScanner(resp.Body)
next := func() string { // the "data:" line of the next event
for lines.Scan() {
if after, ok := strings.CutPrefix(lines.Text(), "data: "); ok {
return after
}
}
return ""
}
fmt.Println(next()) // the snapshot comes first, on every connection
room.PatchElements(`<li>hello</li>`, ypy.WithMode(ypy.ModeAppend), ypy.WithSelector("#messages"))
fmt.Println(next()) // the mode line
fmt.Println(next())
}
Output: elements <ul id="messages"></ul> mode append selector #messages
func NewBroadcaster ¶
func NewBroadcaster(opts ...BroadcasterOption) *Broadcaster
NewBroadcaster returns a broadcaster with no clients.
func (*Broadcaster) Close ¶
func (b *Broadcaster) Close()
Close disconnects every client, refuses new ones and waits until all the handlers have returned. It is safe to call more than once.
func (*Broadcaster) Event ¶
func (b *Broadcaster) Event(name string, detail any, opts ...CustomOption) error
Event publishes a ypy-event, see CustomEvent.
func (*Broadcaster) Len ¶
func (b *Broadcaster) Len() int
Len returns the number of connected clients.
func (*Broadcaster) PatchElements ¶
func (b *Broadcaster) PatchElements(markup string, opts ...ElementsOption) error
PatchElements publishes a ypy-patch-elements event, see PatchElementsEvent.
func (*Broadcaster) PatchSignals ¶
func (b *Broadcaster) PatchSignals(patch any, opts ...SignalsOption) error
PatchSignals publishes a ypy-patch-signals event, see PatchSignalsEvent.
func (*Broadcaster) Publish ¶
func (b *Broadcaster) Publish(ev Event) int
Publish queues ev for every connected client and returns how many received it. A client whose queue is full is dropped.
func (*Broadcaster) Redirect ¶
func (b *Broadcaster) Redirect(url string, opts ...RedirectOption) error
Redirect publishes a ypy-redirect event, see RedirectEvent.
func (*Broadcaster) Refresh ¶
func (b *Broadcaster) Refresh(opts ...RefreshOption) error
Refresh publishes a ypy-refresh event, see RefreshEvent: every connected client fetches its own page again (or the elements of the selector) and morphs the answer in. Use it when a change affects what each client sees but the server cannot, or should not, render one patch for all of them.
func (*Broadcaster) ServeHTTP ¶
func (b *Broadcaster) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP opens an event stream for the request and keeps it open until the client leaves, the client is dropped or the broadcaster is closed. It returns 503 after Broadcaster.Close.
type BroadcasterOption ¶
type BroadcasterOption func(*broadcasterConfig)
BroadcasterOption changes a Broadcaster.
func WithBuffer ¶
func WithBuffer(n int) BroadcasterOption
WithBuffer sets how many events may wait for one slow client. A client that falls further behind is disconnected, and reconnects to a fresh snapshot (see WithSnapshot). The default is 32.
func WithSnapshot ¶
func WithSnapshot(fn func(r *http.Request) ([]Event, error)) BroadcasterOption
WithSnapshot sets the function that returns the full current state for a client that has just connected: the "fat morph" that makes a reconnection safe, because the client needs no memory of what it missed. The events are sent first on every connection, before any published event. An error ends the connection.
func WithStreamOptions ¶
func WithStreamOptions(opts ...StreamOption) BroadcasterOption
WithStreamOptions passes options (keepalive, retry, write timeout) to the stream of every client.
type CSRF ¶
type CSRF struct {
// contains filtered or unexported fields
}
CSRF protects the unsafe requests (everything but GET, HEAD, OPTIONS and TRACE) of a site against cross-site request forgery. It works with the ypy-csrf extension of the client, which sends the token on every same-origin unsafe request without relying on header inheritance.
The token is bound to the session: an HMAC-SHA256, with a key only the server has, of the session identifier, so it needs no storage and a token of one session fails in another. The session identifier is the one the application gives with CSRFSession, and, for a visitor with no session (a login form), a random identifier the middleware keeps in a cookie of its own (HttpOnly, SameSite=Lax, and with the __Host- prefix over TLS).
A CSRF is immutable after NewCSRF and safe for concurrent use.
func NewCSRF ¶
func NewCSRF(key []byte, opts ...CSRFOption) (*CSRF, error)
NewCSRF returns a CSRF that signs its tokens with key, at least MinKeyBytes long (use 32 random bytes); the key is copied. It returns ErrWeakKey for a key that is too short.
func (*CSRF) Check ¶
Check reports whether the request may go on: nil for a safe method, and for an unsafe one that comes from an accepted origin and carries the token of its session, in the header or in the form field. Otherwise it returns ErrCSRFOrigin, ErrCSRFMissing or ErrCSRFInvalid, possibly wrapped. CSRF.Middleware calls it; call it yourself to protect one handler.
func (*CSRF) Field ¶
Field returns a hidden input with the token, for a form that must work without the client (a plain post).
func (*CSRF) Meta ¶
Meta returns the meta tag for the head of the page, which the ypy-csrf extension reads. It has a data-header when the header is not the default.
<head> {{ .CSRFMeta }} </head> <!-- the page data holds csrf.Meta(r) -->
func (*CSRF) Middleware ¶
Middleware refuses the unsafe requests that fail CSRF.Check with a 403 and a plain text body that says what to do, and gives every request a session for the token (see CSRF). It adds Vary: Cookie, since the page holds a token that depends on the cookie. It has the standard net/http shape, so it goes in a chain beside Middleware.
When the token came from a previous key, the response carries YPY-CSRF with the current one. When the token is refused as invalid for a request from an accepted origin (the session changed, perhaps in another tab), the 403 carries YPY-CSRF too, so the client retries with the right token.
func (*CSRF) Renew ¶
func (c *CSRF) Renew(w http.ResponseWriter, r *http.Request)
Renew writes the token of r's session in YPY-CSRF, so the ypy-csrf extension updates its meta tag. Use it when what CSRFSession returns for r is already the new session, or to hand the page a token after the signing key rotated.
func (*CSRF) RenewFor ¶
func (c *CSRF) RenewFor(w http.ResponseWriter, session string)
RenewFor writes in YPY-CSRF the token of an application session. Use it in the handler that changes the session, with the id of the new one:
csrf.RenewFor(w, newSession.ID)
type CSRFOption ¶
type CSRFOption func(*CSRF)
CSRFOption changes a CSRF built by NewCSRF.
func CSRFHeaderName ¶
func CSRFHeaderName(name string) CSRFOption
CSRFHeaderName sets the request header the token is read from, when the page uses a header other than CSRFHeader (the data-header of the meta tag, which CSRF.Meta writes for you).
func CSRFOnFailure ¶
func CSRFOnFailure(fn func(w http.ResponseWriter, r *http.Request, err error)) CSRFOption
CSRFOnFailure replaces the response to a refused request. err is ErrCSRFMissing, ErrCSRFInvalid or ErrCSRFOrigin, possibly wrapped. The handler must write the response, which should be a 403.
func CSRFPreviousKeys ¶
func CSRFPreviousKeys(keys ...[]byte) CSRFOption
CSRFPreviousKeys lists keys that are still accepted while pages made with them are alive; the first key given to NewCSRF signs. A request whose token was made with a previous key is accepted and answered with YPY-CSRF holding the token of the current key, so the page moves on by itself.
func CSRFSecure ¶
func CSRFSecure() CSRFOption
CSRFSecure marks the cookie of the middleware Secure and gives it the __Host- prefix even when the request does not arrive over TLS, for a server behind a proxy that ends TLS.
func CSRFSession ¶
func CSRFSession(fn func(*http.Request) string) CSRFOption
CSRFSession tells the CSRF the session of the request: usually the id of the application's session or of its user. An empty result means the visitor has no session yet, and the cookie of the middleware is used. Call CSRF.Renew or CSRF.RenewFor when the session changes (after a sign-in), so the page holds the token of the new session.
func CSRFTrustedOrigins ¶
func CSRFTrustedOrigins(origins ...string) CSRFOption
CSRFTrustedOrigins lists origins (scheme and host, such as "https://admin.example.com") whose unsafe requests are accepted besides the ones to the host of the request. They still need the token.
type Context ¶
type Context string
Context says where the shell puts a screen.
const ( // ContextDefault puts the screen on the main stack. ContextDefault Context = "default" // ContextModal presents the screen in a sheet with a stack of its own. ContextModal Context = "modal" )
The values of PathProperties.Context.
type CustomOption ¶
type CustomOption func(*customConfig)
CustomOption changes a CustomEvent.
func WithEventTarget ¶
func WithEventTarget(selector string) CustomOption
WithEventTarget names the element the client fires the event on. Without it the client fires it on the document.
type ElementsOption ¶
type ElementsOption func(*elementsConfig)
ElementsOption changes a PatchElementsEvent.
func WithKey ¶
func WithKey(attr string) ElementsOption
WithKey makes an append or prepend patch treat the element as a keyed list: an item whose attribute attr has the value of one already in the list replaces it where it stands instead of being added again. attr is an attribute name such as "id" or "data-id". It is the same rule as the key modifier of the ypy-list extension.
func WithLimit ¶
func WithLimit(n int) ElementsOption
WithLimit makes an append or prepend patch keep at most n items in the list afterwards: the oldest go (the first ones for an append, the last ones for a prepend). n must be at least 1. It is the same rule as the limit modifier of the ypy-list extension.
func WithMode ¶
func WithMode(m PatchMode) ElementsOption
WithMode sets the patch mode. The default is ModeOuter.
func WithNamespace ¶
func WithNamespace(ns Namespace) ElementsOption
WithNamespace sets the namespace the elements are parsed in. The default is NamespaceHTML.
func WithSelector ¶
func WithSelector(sel string) ElementsOption
WithSelector names the element the patch applies to. Without it the client matches each top-level element of the patch with the page element that has the same id.
func WithViewTransition ¶
func WithViewTransition() ElementsOption
WithViewTransition asks the client to apply the patch inside a View Transition when the browser has them.
type Event ¶
type Event struct {
// Name is the SSE event field.
Name string
// ID is the optional SSE id field. Empty means none.
ID string
// Data is one entry per "data:" line. Entries never contain a line break.
Data []string
}
Event is one server-sent event of the YPY protocol, already in the form that goes on the wire: a name, an optional id and the data lines. Build one with PatchElementsEvent, PatchSignalsEvent, RedirectEvent or CustomEvent, send it with Stream.Send or publish it with Broadcaster.Publish.
func CustomEvent ¶
func CustomEvent(name string, detail any, opts ...CustomOption) (Event, error)
CustomEvent builds a ypy-event: the client fires a DOM event called name, with detail (any JSON value, or nil for none) as its detail.
func PatchElementsEvent ¶
func PatchElementsEvent(markup string, opts ...ElementsOption) (Event, error)
PatchElementsEvent builds a ypy-patch-elements event. markup is the HTML to apply; it may be empty with ModeRemove or ModeInner when a selector names the element. It returns an error for an unknown mode or namespace, for a patch that names no element (no selector and no markup), for a selector with a line break, and for WithKey or WithLimit used with any mode but append and prepend, or with an invalid value.
func PatchSignalsEvent ¶
func PatchSignalsEvent(patch any, opts ...SignalsOption) (Event, error)
PatchSignalsEvent builds a ypy-patch-signals event. patch is a JSON Merge Patch (RFC 7396): an object whose keys are set, and whose null values delete a key. A json.RawMessage is used as it is (it must be a valid JSON object); any other value is encoded with encoding/json.
func RedirectEvent ¶
func RedirectEvent(url string, opts ...RedirectOption) (Event, error)
RedirectEvent builds a ypy-redirect event.
func RefreshEvent ¶
func RefreshEvent(opts ...RefreshOption) (Event, error)
RefreshEvent builds a ypy-refresh event: the server says that something changed and each client fetches its own page, or the elements the selector names, again and morphs the answer in. The event carries no HTML, so every client gets what its own session may see.
The event always has a debounce line, because a frame with no data line is not delivered by an SSE client.
type FragmentOption ¶
type FragmentOption func(*fragmentConfig)
FragmentOption changes what the SDK says about a fragment. It is accepted by Fragment, FragmentStatus, ValidationError, Partial and NewMiddleware.
func AllowIndex ¶
func AllowIndex() FragmentOption
AllowIndex turns off the "X-Robots-Tag: noindex" header that a fragment gets by default. Use it for a fragment that is a page on its own, one that a crawler should be able to index. "Vary: YPY-Request" is still added, because that one keeps a cache from mixing fragments and pages.
type LayerMode ¶
type LayerMode string
LayerMode is the kind of a layer of the ypy-layers extension.
const ( // LayerModal is a centered modal dialog; the page behind is inert. LayerModal LayerMode = "modal" // LayerDrawer is a modal that sticks to an edge, see [LayerOptions.Side]. LayerDrawer LayerMode = "drawer" // LayerPopup is a non-modal dialog anchored to its opener. LayerPopup LayerMode = "popup" )
type LayerOptions ¶
type LayerOptions struct {
// URL is what the layer loads. [OpenLayer] sets it.
URL string `json:"url,omitempty"`
// HTML is the markup the layer shows instead of loading a URL.
// [OpenLayerHTML] sets it. Escape user data in it.
HTML string `json:"html,omitempty"`
// Mode is the kind of layer. The client's default is a modal.
Mode LayerMode `json:"mode,omitempty"`
// CloseOn lists client events that accept the layer: the first one fired
// from inside it closes it, with the event detail as its value.
CloseOn []string `json:"closeOn,omitempty"`
// CloseOnURL lists path patterns ("*" is a wildcard): a request of the
// layer that ends at a matching path accepts it.
CloseOnURL []string `json:"closeOnUrl,omitempty"`
// CloseOnFragment is a selector: a response that holds a match accepts the
// layer.
CloseOnFragment string `json:"closeOnFragment,omitempty"`
// History shows the layer URL in the address bar while it is open. Nil
// keeps the client's setting.
History *bool `json:"history,omitempty"`
// Side is the edge of a drawer.
Side LayerSide `json:"side,omitempty"`
// Label is the accessible name of the layer (aria-label).
Label string `json:"label,omitempty"`
// Outside is whether a click outside dismisses the layer. Nil keeps the
// client's setting (true); use new(false) to turn it off.
Outside *bool `json:"outside,omitempty"`
// Escape is whether Esc dismisses the layer. Nil keeps the client's
// setting (true); use new(false) to turn it off.
Escape *bool `json:"escape,omitempty"`
// Class is the classes of the dialog element.
Class string `json:"class,omitempty"`
}
LayerOptions is what OpenLayer and OpenLayerHTML put in the YPY-Open-Layer header. Every field is optional; what is left out keeps the client's configuration. The names are the keys the ypy-layers extension reads and nothing else is sent.
type LocationOptions ¶
type LocationOptions struct {
// Path is the URL to fetch.
Path string `json:"path"`
// Target is the selector of the element the response goes into.
Target string `json:"target,omitempty"`
// Swap is the swap style.
Swap string `json:"swap,omitempty"`
// Select is the selector of the content taken from the response.
Select string `json:"select,omitempty"`
// Push is "true", "false" or a URL to push on the history. Empty means the
// client default (push the path).
Push string `json:"push,omitempty"`
// Replace is "true", "false" or a URL that replaces the current history entry.
Replace string `json:"replace,omitempty"`
// Values are extra parameters sent with the request.
Values map[string]any `json:"values,omitempty"`
// Headers are extra request headers.
Headers map[string]string `json:"headers,omitempty"`
}
LocationOptions is the object form of the YPY-Location header: a navigation that fetches Path with the YPY client and swaps the answer in, without a full page load. Only Path is required.
type Manifest ¶
type Manifest struct {
// contains filtered or unexported fields
}
Manifest is the manifest "ypy gen assets" writes: for each origin (a directory, or a template with --group template) the hashed CSS and script files extracted from the templates. It holds the SHA-384 of each file, read once when it is loaded, so every page can carry the integrity attribute.
A Manifest is immutable and safe for concurrent use.
func LoadManifest ¶
LoadManifest reads the manifest at path in fsys and the files it names, which sit relative to the manifest. A name that escapes that directory, or a file that is missing, is an error: a deployment that lost an asset fails when the server starts, not when the first page is served.
//go:embed assets var assetsFS embed.FS m, err := ypy.LoadManifest(assetsFS, "assets/manifest.json")
func (*Manifest) Assets ¶
Assets returns the tags that load the stylesheet and the script of an origin, to be put in a template where the page's head (or the end of its body) is:
<link rel="stylesheet" href="/assets/ui.1a2b3c4d5e.css" integrity="sha384-..."> <script src="/assets/ui.9f8e7d6c5b.js" defer integrity="sha384-..."></script>
When the page has a nonce for its Content-Security-Policy, pass it as the second argument and both tags carry it. An origin the manifest does not know, or one that has no CSS or no script, gives nothing for that part. The attributes are escaped, and nothing here is inline: the policy needs no 'unsafe-inline'.
Example ¶
package main
import (
"html/template"
"os"
"testing/fstest"
ypy "github.com/ypy-develop/go"
)
func main() {
fsys := fstest.MapFS{
"manifest.json": {Data: []byte(`{"ui": {"css": "ui.1a2b3c4d5e.css"}}`)},
"ui.1a2b3c4d5e.css": {Data: []byte("a{}")},
}
m, _ := ypy.LoadManifest(fsys, "manifest.json")
tmpl := template.Must(template.New("page").Funcs(m.FuncMap()).Parse(`{{ assets "ui" .Nonce }}`))
tmpl.Execute(os.Stdout, map[string]string{"Nonce": "r4nd0m"})
}
Output: <link rel="stylesheet" href="/assets/ui.1a2b3c4d5e.css" integrity="sha384-m4Zcd9m9Kerya2aMKZ9CuL1yv7QLjdpmEo79GaQCk1uO2U4trsxWuyqSJsOzpOru" nonce="r4nd0m">
func (*Manifest) FuncMap ¶
FuncMap returns the template function "assets" for html/template:
tmpl := template.Must(template.New("page").Funcs(m.FuncMap()).Parse(src))
{{ assets "ui" }} or {{ assets "ui" .Nonce }}
func (*Manifest) Handler ¶
Handler serves the files of the manifest at Manifest.WithBase's prefix with a cache that never expires, since a new content has a new name. It serves those files and nothing else of the file system, the manifest itself included, and only GET and HEAD.
mux.Handle("/assets/", m.Handler())
func (*Manifest) Integrity ¶
Integrity returns the integrity value ("sha384-...") of a file of the manifest, as it is written in the manifest.
func (*Manifest) WithBase ¶
WithBase returns a copy of the manifest whose URLs start with base: a path ("/static/") or an absolute URL ("https://cdn.example/a/"). A missing trailing slash is added. The default is DefaultAssetsBase.
type ModalStyle ¶
type ModalStyle string
ModalStyle is how a modal screen is presented.
const ( ModalMedium ModalStyle = "medium" ModalLarge ModalStyle = "large" ModalFull ModalStyle = "full" ModalDrawer ModalStyle = "drawer" )
The values of PathProperties.ModalStyle.
type ModelOption ¶
type ModelOption func(*modelConfig)
ModelOption changes a ModelStream.
func WithAnnounce ¶
func WithAnnounce(start, ready, stopped, failed string) ModelOption
WithAnnounce sets the texts the page says in its live region: when the answer starts, when it is ready, when it was stopped and when it failed (the last two assertively). They go to the container as the attributes ypy-announce-start, ypy-announce, ypy-announce-stop and ypy-announce-error; an empty text says nothing. Take them from the translation of the application.
func WithAnswerID ¶
func WithAnswerID(id string) ModelOption
WithAnswerID sets the id of the answer container; the regions get the id plus "-done" and "-tail". The default is a random id. It must start with a letter and have only letters, digits, "_" and "-".
func WithFailText ¶
func WithFailText(s string) ModelOption
WithFailText sets the text added to an answer that failed, see ModelStream.Fail.
func WithFlushBytes ¶
func WithFlushBytes(n int) ModelOption
WithFlushBytes sets how much unsent text makes a write flush at once (4096 by default).
func WithFlushInterval ¶
func WithFlushInterval(d time.Duration) ModelOption
WithFlushInterval sets how often buffered text is sent (50 ms by default, at most 20 patches a second). Zero or less turns the timer off: text is then sent when a block closes, when the buffer passes WithFlushBytes, on ModelStream.Flush and at the end. Tests use zero.
func WithFollow ¶
func WithFollow() ModelOption
WithFollow adds ypy-follow to the container: the page follows the growing answer while the user is at the bottom of it.
func WithMaxBytes ¶
func WithMaxBytes(n int) ModelOption
WithMaxBytes sets the cap of one answer in bytes of model text (1 MiB by default). The write that passes it ends the answer as a stop.
func WithModelTarget ¶
func WithModelTarget(selector string, mode PatchMode) ModelOption
WithModelTarget sets where the answer container goes: the selector of an element of the page and the mode of the patch, ModeAppend by default (the answer is added as the last child). The target is required, and it is always a value of the application, never taken from the model.
func WithPlainText ¶
func WithPlainText() ModelOption
WithPlainText is the low-cost mode for many tokens: no Markdown and no regions. The container has one child, and each flush is one event that appends the escaped new text to it. Style it with white-space: pre-wrap.
func WithRenderer ¶
func WithRenderer(r Renderer) ModelOption
WithRenderer sets the Markdown renderer, see Renderer and BlockRenderer.
func WithShortAnswer ¶
func WithShortAnswer() ModelOption
WithShortAnswer is the simplest correct form, for answers under about 2 KiB: no regions, and every flush sends the whole container as one outer patch.
func WithStopText ¶
func WithStopText(s string) ModelOption
WithStopText sets the text added to an answer that was stopped (by the user, by the byte cap or by ModelStream.Cancel). It is plain text of the application, never a message of the provider.
type ModelStream ¶
type ModelStream struct {
// contains filtered or unexported fields
}
A ModelStream writes the answer of a language model into the page as it is generated, following ADR-0018. It is an io.Writer for the text of the model, over a Stream; the application adapts its provider's stream to Write and gives ModelStream.Context to the provider call.
The container is patched into the page when the ModelStream is created:
<article id="a42" ypy-untrusted aria-busy="true" aria-live="off"> <div id="a42-done"></div> closed Markdown blocks: append only <div id="a42-tail"></div> the open block: replaced at each flush </article>
Text is buffered and sent when the timer fires, when a block closes, when the buffer is large, and at the end. The events of one flush go in one write. Close sends one outer patch with the complete final HTML, so a client that missed events ends correct. While the connection is slow only the newest text of the open block is kept, and closed blocks are never skipped.
The policy is bound: when the connection ends, ModelStream.Context is cancelled and writes fail, so the provider request is freed. A detached generation, one that outlives the connection and lets a reconnect continue, is the application's registry: it keeps the answer (ModelStream.Text) and opens a new ModelStream on the reconnected stream with the text so far.
Whatever the model writes goes through the Renderer and nothing else: the selectors, modes and ids are constants of the application. A ModelStream is safe for concurrent use.
Example ¶
A handler that streams a model answer into the page. The model's text goes through a Markdown renderer that never copies HTML, so it is safe to show.
// SPDX-License-Identifier: MIT
package main
import (
"fmt"
"net/http"
"net/http/httptest"
ypy "github.com/ypy-develop/go"
"github.com/ypy-develop/go/ypymd"
"github.com/ypy-develop/go/ypytest"
)
// fakeModel stands for a provider client: it hands out the tokens of an answer.
func fakeModel() []string {
return []string{"Hello", ", **wor", "ld**.", "\n\n", "- one\n", "- two"}
}
// A handler that streams a model answer into the page. The model's text goes
// through a Markdown renderer that never copies HTML, so it is safe to show.
func main() {
h := ypy.StreamFunc(func(s *ypy.Stream, r *http.Request) error {
answer, err := ypy.NewModelStream(s,
ypy.WithModelTarget("#chat", ypy.ModeAppend),
ypy.WithAnswerID("a1"),
ypy.WithRenderer(ypymd.Renderer{}), // arandu-markdown in an Arandu application
ypy.WithAnnounce("Answer started", "Answer ready", "Stopped", "Failed"),
ypy.WithStopText("Stopped."),
ypy.WithFlushInterval(0), // the default is 50 ms; zero keeps this example exact
)
if err != nil {
return err
}
// pass answer.Context() to the provider request, so a stop or a lost
// connection frees the call
for _, token := range fakeModel() {
if _, err := answer.WriteString(token); err != nil {
return err // the answer ended or the client left
}
}
return answer.Close()
})
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/ask", nil))
answer, _ := ypytest.ApplyAnswer("a1", ypytest.ParseEvents(rec.Body.String()))
fmt.Println(answer.State)
fmt.Println(answer.Body())
}
Output: done <p>Hello, <strong>world</strong>.</p><ul><li>one</li><li>two</li></ul>
func NewModelStream ¶
func NewModelStream(s *Stream, opts ...ModelOption) (*ModelStream, error)
NewModelStream starts an answer on s: it sends the container and, unless the interval is zero, starts the flush timer. Close, Cancel or Fail must be called before the handler returns.
func (*ModelStream) Cancel ¶
func (m *ModelStream) Cancel() error
Cancel ends the answer as a stop: the final patch has what was written, data-ypy-answer="stopped" and the stop text. Call it when the user pressed Stop (the application's own endpoint) or when a limit is passed. Cancelling twice, or after the end, does nothing.
func (*ModelStream) Close ¶
func (m *ModelStream) Close() error
Close ends the answer normally: it sends what is buffered and one outer patch with the complete final HTML, without aria-busy and with data-ypy-answer="done". It does nothing after the answer ended.
func (*ModelStream) Context ¶
func (m *ModelStream) Context() context.Context
Context is cancelled when the connection ends and when the answer ends in any way. Give it to the provider request, so cancelling frees the call.
func (*ModelStream) Fail ¶
func (m *ModelStream) Fail() error
Fail ends the answer as a failure: data-ypy-answer="failed" and the fail text of the application. Never put the error of the provider in the page.
func (*ModelStream) Flush ¶
func (m *ModelStream) Flush() error
Flush sends what is buffered now. The timer, a closed block and a large buffer call it for you.
func (*ModelStream) ID ¶
func (m *ModelStream) ID() string
ID returns the id of the answer container.
func (*ModelStream) Text ¶
func (m *ModelStream) Text() string
Text returns the text of the model received so far.
func (*ModelStream) Write ¶
func (m *ModelStream) Write(p []byte) (int, error)
Write adds text of the model to the answer. It never splits a UTF-8 sequence: an incomplete rune waits for its continuation. It returns ErrModelDone after the answer ended, the context error when the connection is gone, and ErrModelLimit when the byte cap is passed (the answer then ends as a stop).
func (*ModelStream) WriteString ¶
func (m *ModelStream) WriteString(s string) (int, error)
WriteString is like Write for a string.
type Namespace ¶
type Namespace string
Namespace is the XML namespace the elements of a patch are parsed in.
type Native ¶
type Native struct {
// Platform is the shell's platform: "ios", "android", "desktop" or another
// lower-case token the shell chose.
Platform string
// Version is the version of the bridge protocol the shell speaks (1..9999).
Version int
// contains filtered or unexported fields
}
Native is what a request says about the native app shell that made it (ADR-0017). It is read from HeaderNative, which the ypy-native extension sends on every YPY request, or, when the header is absent (the first load of a screen, before any script runs), from the "YpyNative/<n> (<platform>)" suffix of the user-agent; in that case Caps is empty.
Decide on capabilities with Native.Has, never on Version: the app is released on its own cadence, and a build that lacks a component must keep working against a new server (the markup is the fallback). An answer that varies on it MUST carry "Vary: YPY-Native, User-Agent", see VaryNative.
The values come from the client and are only a hint to shape the HTML; they grant nothing. The zero value is an ordinary browser.
func NewNative ¶
NewNative builds a Native, for a test or a handler that wants to act as if the app had sent it. A capability that is not a valid token is dropped.
func ParseNative ¶
ParseNative parses the value of HeaderNative, "<platform>; v=<n>; caps=<a,b,c>". It is strict: a platform that is not a lower-case token, a version outside 1..9999 or a missing one makes the whole value invalid (the zero Native and false). An invalid capability token is dropped, and at most 64 are kept. It never panics.
func (Native) Caps ¶
Caps names the native components the installed build knows, in the order the shell listed them. It is a new slice on every call.
type PartialSpec ¶
type PartialSpec struct {
// Target is a selector for the element that receives the content. It is
// written as the ypy-target attribute.
Target string
// Swap is the swap style (written as ypy-swap). Empty means the client default.
Swap string
// ID is written as the id attribute. Without a Target, the client uses
// #ID as the target.
ID string
}
PartialSpec says where a <ypy-partial> goes.
func (PartialSpec) HTML ¶
func (p PartialSpec) HTML(markup string) (string, error)
HTML returns the <ypy-partial> element for markup. Attribute values are escaped; markup is written as it is. It returns an error when the spec names no target at all (neither Target nor ID), because the client could not place the content.
type PatchMode ¶
type PatchMode string
PatchMode is how the elements of a patch are applied to the page.
const ( ModeOuter PatchMode = "outer" // morph the matched element with the new element (default) ModeInner PatchMode = "inner" // morph the children of the matched element ModeReplace PatchMode = "replace" // replace the matched element, no morph ModeAppend PatchMode = "append" // add the content as the last children ModePrepend PatchMode = "prepend" // add the content as the first children ModeBefore PatchMode = "before" // add the content before the matched element ModeAfter PatchMode = "after" // add the content after the matched element ModeRemove PatchMode = "remove" // remove the matched element )
The patch modes. Outer and Inner morph the existing DOM (state such as focus, scroll and form values survives); Replace swaps without morphing.
type PathConfig ¶
type PathConfig struct {
// Version is the version of the document format, at least 1.
Version int `json:"version"`
Settings PathSettings `json:"settings"`
Rules []PathRule `json:"rules"`
}
PathConfig is the path configuration document of ADR-0017: one JSON file the shell fetches at launch and on resume, so a route change needs a deploy and not a store review. Serve it at NativePathConfigPath with PathConfig.Handler.
func (PathConfig) Handler ¶
func (c PathConfig) Handler() (http.Handler, error)
Handler returns an http.Handler that serves the document: it validates the configuration, encodes it once, and answers GET and HEAD with a strong ETag (the SHA-256 of the body), "Cache-Control: no-cache" and 304 to a matching If-None-Match. Any other method gets 405. Mount it at NativePathConfigPath:
h, err := cfg.Handler()
mux.Handle("GET "+ypy.NativePathConfigPath, h)
func (PathConfig) Validate ¶
func (c PathConfig) Validate() error
Validate checks the document: a version of at least 1, patterns that compile, values from the vocabulary, tab paths that start with "/" and bridge origins that are scheme://host[:port] (https, or http for localhost).
type PathProperties ¶
type PathProperties struct {
// Context is where the screen goes.
Context Context `json:"context,omitempty"`
// ModalStyle is how a modal is presented.
ModalStyle ModalStyle `json:"modal_style,omitempty"`
// Presentation is what a visit does to the stack.
Presentation Presentation `json:"presentation,omitempty"`
// View is "web" (a web view) or "native:<name>" (a native screen the app
// registered).
View string `json:"view,omitempty"`
// PullToRefresh is whether the native refresh gesture reloads the screen.
PullToRefresh *bool `json:"pull_to_refresh,omitempty"`
// QueryString is whether the query is part of the screen's identity.
QueryString QueryString `json:"query_string,omitempty"`
}
PathProperties is the closed vocabulary of a rule. A property left empty is not set, so a later rule that matches the same URL only overrides what it names. A client ignores a property it does not know, which lets the document grow.
type PathRule ¶
type PathRule struct {
// Patterns are regular expressions; keep to the subset that Go, Swift,
// Kotlin and JavaScript all accept.
Patterns []string `json:"patterns"`
Properties PathProperties `json:"properties"`
}
PathRule applies Properties to every URL, path plus query, that one of the Patterns matches. All matching rules apply in order, later properties overriding earlier ones.
type PathSettings ¶
type PathSettings struct {
// Tabs is the tab bar.
Tabs []PathTab `json:"tabs,omitempty"`
// BridgeOrigins are the origins to which the shell attaches the bridge
// channel, as scheme://host[:port].
BridgeOrigins []string `json:"bridge_origins,omitempty"`
}
PathSettings are the app-wide settings of the document.
type Presentation ¶
type Presentation string
Presentation is what a visit to a URL does to the stack.
const ( // PresentPush adds a screen. PresentPush Presentation = "push" // PresentReplace swaps the top screen. PresentReplace Presentation = "replace" // PresentReplaceRoot resets the stack to this screen. PresentReplaceRoot Presentation = "replace_root" // PresentPop closes the current screen. PresentPop Presentation = "pop" // PresentRefresh reloads the screen below. PresentRefresh Presentation = "refresh" // PresentNone leaves the decision to YPY inside the current page. PresentNone Presentation = "none" )
The values of PathProperties.Presentation.
type QueryString ¶
type QueryString string
QueryString says whether two URLs that differ only by query are one screen.
const ( QueryIgnore QueryString = "ignore" QueryKeep QueryString = "keep" )
The values of PathProperties.QueryString.
type RedirectMode ¶
type RedirectMode string
RedirectMode is how the client navigates on a ypy-redirect event.
const ( RedirectReplace RedirectMode = "replace" // navigate, replacing the current history entry RedirectHard RedirectMode = "hard" // a full page load )
The redirect modes.
type RedirectOption ¶
type RedirectOption func(*RedirectMode)
RedirectOption changes a RedirectEvent.
func WithRedirectMode ¶
func WithRedirectMode(m RedirectMode) RedirectOption
WithRedirectMode sets how the client navigates. The default is RedirectNavigate.
type RefreshOption ¶
type RefreshOption func(*refreshConfig)
RefreshOption changes a RefreshEvent.
func WithRefreshDebounce ¶
func WithRefreshDebounce(d time.Duration) RefreshOption
WithRefreshDebounce sets the window in which the client joins refresh events into one request. The default is DefaultRefreshDebounce; the limit is one minute.
func WithRefreshJitter ¶
func WithRefreshJitter(d time.Duration) RefreshOption
WithRefreshJitter makes each client wait a random time, up to d, after the debounce before it fetches. It spreads the requests of many clients that received the same event. The limit is one minute.
func WithRefreshSelector ¶
func WithRefreshSelector(selector string) RefreshOption
WithRefreshSelector limits the refresh to the elements that match selector: each one that has a ypy-get is fetched again and morphed. Without it the client fetches its whole page again.
type Renderer ¶
Renderer turns the Markdown a model wrote into HTML. It decides what the page will show of untrusted text, so it MUST emit only safe HTML: no script, no event handler, no ypy-* attribute, and no URL scheme but http, https and mailto (see ADR-0018 item 5). The package ypymd has one; the SDK itself ships only a plain-text renderer that escapes.
type Request ¶
type Request struct {
// IsYPY is true when the YPY client made the request.
IsYPY bool
// Boosted is true when the request comes from a boosted link or form.
Boosted bool
// HistoryRestore is true when the client restores a page from the history.
// It comes without IsYPY, and the answer must be a full page.
HistoryRestore bool
// Target identifies the element the response goes into, as tag#id.
Target string
// Source identifies the element that made the request, as tag#id.
Source string
// RequestType is [RequestFull], [RequestPartial] or empty when the header
// is absent or has an unknown value.
RequestType RequestType
// CurrentURL is the URL of the page that made the request.
CurrentURL string
// Prompt is the answer the user typed in a prompt, already decoded.
Prompt string
// Validate is the name of the field the ypy-validate extension is
// checking, or empty when the request is not a field check. A handler that
// also serves the real action must test it first (see [Request.IsValidation])
// and answer without changing anything.
Validate string
// Layer is the kind of layer ("modal", "drawer" or "popup") the response
// fills, as the ypy-layers extension sent it, or empty when the request is
// not made for a layer. An answer to a layer request usually leaves out the
// page chrome.
Layer string
// Native says that the request comes from a native app shell, and which
// one; the zero value is a request from an ordinary browser. Decide on
// [Native.Has] (the capabilities of the installed build), never on the
// version: an old app keeps working against a new server.
Native Native
}
Request is what the YPY headers of an HTTP request say. The zero value is a request that did not come from the YPY client.
func FromContext ¶
FromContext returns the request stored by Middleware. Without the middleware it returns the zero Request, which reads as "not a YPY request".
func FromRequest ¶
FromRequest reads the YPY headers of r. It does not read the body.
Example ¶
package main
import (
"fmt"
"net/http/httptest"
ypy "github.com/ypy-develop/go"
)
func main() {
r := httptest.NewRequest("GET", "/feed", nil)
r.Header.Set("YPY-Request", "true")
r.Header.Set("YPY-Target", "div#feed")
r.Header.Set("YPY-Request-Type", "partial")
q := ypy.FromRequest(r)
fmt.Println(q.IsYPY, q.Target, q.IsPartial())
}
Output: true div#feed true
Example (Native) ¶
package main
import (
"fmt"
"net/http/httptest"
ypy "github.com/ypy-develop/go"
)
func main() {
r := httptest.NewRequest("GET", "/orders", nil)
r.Header.Set(ypy.HeaderNative, "ios; v=1; caps=share,date-picker")
q := ypy.FromRequest(r)
fmt.Println(q.IsNative(), q.Native.Platform, q.Native.Has("share"), q.Native.Has("camera"))
}
Output: true ios true false
func (Request) IsPartial ¶
IsPartial reports whether the response should be a fragment rather than a full page: a YPY request that did not ask for the full content.
func (Request) IsValidation ¶
IsValidation reports whether the request is a field check of the ypy-validate extension. Such a request goes to a real handler, often the one of the form itself: answer it with the field's error or nothing, and do not run the action.
type RequestType ¶
type RequestType string
RequestType tells how much of the page a request expects back.
const ( // RequestFull is a request whose response replaces the page content (the // target is the body, or a selector picks the content out of a full page). RequestFull RequestType = "full" // RequestPartial is a request whose response fills a smaller target. RequestPartial RequestType = "partial" )
type SignalsOption ¶
type SignalsOption func(*signalsConfig)
SignalsOption changes a PatchSignalsEvent.
func WithOnlyIfMissing ¶
func WithOnlyIfMissing() SignalsOption
WithOnlyIfMissing makes the client apply only the keys the signals do not have yet: existing values are kept. Use it to send defaults.
type SignatureError ¶
type SignatureError struct {
// Signal is the name of the signal.
Signal string
// Err is [ErrSignatureMissing] or [ErrSignatureInvalid].
Err error
// Detail adds to the message what exactly is missing, when that is not
// obvious.
Detail string
}
SignatureError says which signal failed verification. errors.Is tells the two causes apart: ErrSignatureMissing and ErrSignatureInvalid.
func (*SignatureError) Error ¶
func (e *SignatureError) Error() string
func (*SignatureError) Unwrap ¶
func (e *SignatureError) Unwrap() error
type Signer ¶
type Signer struct {
// contains filtered or unexported fields
}
Signer signs the signals the server owns and verifies them when they come back from the client. The client can read such a signal, and the ypy-signals extension refuses to write it, but whoever controls the browser can send any value: the signature is what lets the server notice.
A signature is an HMAC-SHA256, with a key only the server has, of the signal's name and value, written in the canonical JSON form of RFC 8785 so that it does not depend on key order or number formatting. Verification compares in constant time.
To rotate a key, make a Signer with the new key first and the old ones after it: it signs with the first and accepts any. A Signer is immutable and safe for concurrent use.
Example ¶
A server signs the value of a read-only signal when it sends it, and checks the signature when the value comes back.
package main
import (
"bytes"
"errors"
"fmt"
ypy "github.com/ypy-develop/go"
)
func main() {
key := bytes.Repeat([]byte("k"), ypy.MinKeyBytes)
signer, _ := ypy.NewSigner(key)
sig, _ := signer.Sign("plan", "free")
fmt.Println(signer.Verify("plan", "free", sig))
// The user changed the value in the browser.
err := signer.Verify("plan", "pro", sig)
fmt.Println(err)
fmt.Println(errors.Is(err, ypy.ErrSignatureInvalid))
}
Output: <nil> ypy: signal "plan": signature does not match true
func NewSigner ¶
NewSigner returns a Signer that signs with key and verifies with key and with each of previous, which are keys still accepted while clients hold values signed with them. Every key must have at least MinKeyBytes bytes (use 32 random bytes); the keys are copied.
func (*Signer) Bind ¶
Bind returns a Signer that signs and verifies only for binding, usually the id of the session or of the user: a value signed for one session does not verify in another, so a client cannot hand its signed values to someone else. The Signer it is called on is unchanged.
func (*Signer) Declaration ¶
Declaration returns the value of a ypy-signals.server attribute for values, an object: the values and their signatures, as one JSON object, which the extension reads as the declaration of server-owned signals. Escape it as any attribute value (html/template does). Names are as in Signer.SignPatch.
<div ypy-signals.server="{{ .Declaration }}">
func (*Signer) Sign ¶
Sign returns the signature of the signal name with this value: "v1." and the unpadded base64url of the HMAC. value is anything encoding/json can encode.
func (*Signer) SignPatch ¶
SignPatch returns patch with the signatures added: the same object, plus the SignatureSignal key holding one signature for each signal it signs. The result is a JSON Merge Patch to send with PatchSignals, Stream.PatchSignals or Broadcaster.PatchSignals; merged into the client's signals, it changes the values and their signatures together.
patch must encode as a JSON object. With no names it signs every signal of the patch that is not local (a name starting with an underscore never comes back, so there is nothing to verify); with names it signs only those, and each must be in the patch. A signal set to null is a deletion: its signature is deleted with it.
The client merges an object into the value it already holds, so a signed value should be a string, a number, a boolean or an array, which replace the old value as a whole, or an object that always has the same keys.
func (*Signer) Verify ¶
Verify checks the signature of the signal name with this value, with the current key and with the previous ones. It returns a *SignatureError with ErrSignatureMissing when signature is empty and ErrSignatureInvalid when it does not match.
func (*Signer) VerifySignals ¶
VerifySignals checks the signals document the client sent (see RawSignals) for each of names: the signal must be there and its signature must match. It returns the first failure as a *SignatureError (ErrSignatureMissing when the signal or its signature is absent, ErrSignatureInvalid when they do not match), and an error when no names are given, because a check of nothing would pass silently.
type Stream ¶
type Stream struct {
// contains filtered or unexported fields
}
Stream is a server-sent event response in the YPY protocol. It is safe for concurrent use: many goroutines may send, and each event is written whole.
Always call Stream.Close (with defer) before the handler returns: it stops the keepalive goroutine, and nothing may write to the response after the handler is gone.
func NewStream ¶
func NewStream(w http.ResponseWriter, r *http.Request, opts ...StreamOption) (*Stream, error)
NewStream starts an event stream on w: it sets the SSE headers, sends them with a first flush and starts the keepalive. It returns an error when the response writer cannot flush (nothing is written then; answer with http.Error). The stream ends when the client disconnects (r's context is done) or when Close is called.
Example ¶
package main
import (
"fmt"
"net/http"
ypy "github.com/ypy-develop/go"
"github.com/ypy-develop/go/ypytest"
)
func main() {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s, err := ypy.NewStream(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer s.Close()
s.PatchElements(`<p id="status">Working</p>`)
s.PatchSignals(map[string]any{"progress": 50})
s.Event("job:done", map[string]int{"id": 7})
s.Redirect("/jobs/7")
})
res := ypytest.Do(handler, ypytest.NewRequest("GET", "/jobs/7/events"))
fmt.Print(res.Body())
}
Output: event: ypy-patch-elements data: elements <p id="status">Working</p> event: ypy-patch-signals data: signals {"progress":50} event: ypy-event data: name job:done data: detail {"id":7} event: ypy-redirect data: url /jobs/7
func (*Stream) Close ¶
func (s *Stream) Close()
Close ends the stream: it stops the keepalive goroutine and waits for it. It is safe to call more than once. It does not close the connection: that happens when the handler returns.
func (*Stream) Context ¶
Context returns the context of the request: it is done when the client disconnects.
func (*Stream) Done ¶
func (s *Stream) Done() <-chan struct{}
Done is closed when the client has disconnected. Wait on it in the handler.
func (*Stream) Event ¶
func (s *Stream) Event(name string, detail any, opts ...CustomOption) error
Event sends a ypy-event, see CustomEvent.
func (*Stream) PatchElements ¶
func (s *Stream) PatchElements(markup string, opts ...ElementsOption) error
PatchElements sends a ypy-patch-elements event, see PatchElementsEvent.
func (*Stream) PatchSignals ¶
func (s *Stream) PatchSignals(patch any, opts ...SignalsOption) error
PatchSignals sends a ypy-patch-signals event, see PatchSignalsEvent.
func (*Stream) Redirect ¶
func (s *Stream) Redirect(url string, opts ...RedirectOption) error
Redirect sends a ypy-redirect event, see RedirectEvent.
func (*Stream) Refresh ¶
func (s *Stream) Refresh(opts ...RefreshOption) error
Refresh sends a ypy-refresh event, see RefreshEvent.
func (*Stream) Send ¶
Send writes one event. It returns the context error when the client is gone, ErrStreamClosed after Close, and the write error otherwise; after an error the stream is finished.
func (*Stream) SendBatch ¶
SendBatch writes several events in one write and one flush, so they travel together and the client applies them in one task. It is the same as calling Stream.Send for each, with the cost of one write; an empty list writes nothing.
type StreamOption ¶
type StreamOption func(*streamConfig)
StreamOption changes a Stream.
func WithKeepAlive ¶
func WithKeepAlive(d time.Duration) StreamOption
WithKeepAlive sets how long the stream may stay silent before a comment line is sent to keep proxies and the browser from closing it. The default is 15 seconds; zero or less turns it off.
func WithRetry ¶
func WithRetry(d time.Duration) StreamOption
WithRetry sets the reconnection delay the client is told to use (the SSE retry field), written once at the start. The default is to send none.
func WithWriteTimeout ¶
func WithWriteTimeout(d time.Duration) StreamOption
WithWriteTimeout sets how long one write may block on a slow client before the stream gives up. The deadline is renewed on every write, so a server-wide WriteTimeout does not cut a long-lived stream. The default is 10 seconds.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
canonjson
Package canonjson writes JSON in the canonical form of RFC 8785 (the JSON Canonicalization Scheme): no white space, object members sorted by their UTF-16 code units, numbers as the shortest IEEE-754 double in the form of ECMAScript's Number-to-String, and strings with the minimal escapes.
|
Package canonjson writes JSON in the canonical form of RFC 8785 (the JSON Canonicalization Scheme): no white space, object members sorted by their UTF-16 code units, numbers as the shortest IEEE-754 double in the form of ECMAScript's Number-to-String, and strings with the minimal escapes. |
|
mergepatch
Package mergepatch applies a JSON Merge Patch (RFC 7396).
|
Package mergepatch applies a JSON Merge Patch (RFC 7396). |
|
Package ypymd renders the Markdown a language model writes into HTML that is safe by construction, and can do it block by block while the text is still arriving.
|
Package ypymd renders the Markdown a language model writes into HTML that is safe by construction, and can do it block by block while the text is still arriving. |
|
Package ypytest tests YPY handlers without a browser.
|
Package ypytest tests YPY handlers without a browser. |