Documentation
¶
Overview ¶
Package oembed implements the oEmbed 1.0 specification (https://oembed.com) as a consumer.
Given a URL, Client.Fetch finds the matching oEmbed endpoint — via the embedded provider registry, the response's Link header, or HTML discovery, in that order — calls it, and returns a validated Response. Callers that already hold the response use Client.FetchHTML instead, which runs the same pipeline against the supplied header and body.
Those two are the whole client. The intermediate steps — Link-header parsing, HTML discovery, and calling a resolved endpoint — are deliberately unexported, so there is one way to fetch and no way to assemble a half-guarded pipeline by hand.
Rendering ¶
Response.HTML is arbitrary provider-controlled markup and is never sanitized, because sanitizing it would strip the embed. Response.Embed classifies a response into one of three render plans — EmbedIframe, EmbedSandbox, or EmbedLink — so that markup reaches a page only inside a frame. Never write Response.HTML directly.
Authoring ¶
The NewLink, NewPhoto, NewVideo, and NewRich builders produce documents that cannot be spec-invalid by construction, Response.Validate is the strict specification check for documents you author, and WriteResponse validates and encodes one to an http.ResponseWriter in JSON or XML. These are the response document itself, not a provider framework: request parsing and endpoint advertisement are out of scope.
Index ¶
- Constants
- func WriteResponse(w http.ResponseWriter, response Response, format string) error
- type Client
- type ClientOption
- func WithAllowPrivateIPs(allow bool) ClientOption
- func WithMaxBodySize(maxBytes int64) ClientOption
- func WithMaxHeight(maxHeight int) ClientOption
- func WithMaxWidth(maxWidth int) ClientOption
- func WithRegistry(registry Registry) ClientOption
- func WithRoundTripper(wrap func(next http.RoundTripper) http.RoundTripper) ClientOption
- func WithUserAgent(userAgent string) ClientOption
- type Embed
- type EmbedIframe
- type EmbedLink
- type EmbedPolicy
- type EmbedSandbox
- type Endpoint
- type Provider
- type ProviderEndpoint
- type Registry
- type Response
Examples ¶
Constants ¶
const ContentTypeJSONOEmbed = "application/json+oembed"
ContentTypeJSONOEmbed is the link type advertising a JSON oEmbed endpoint
const ContentTypeXMLOEmbed = "text/xml+oembed"
ContentTypeXMLOEmbed is the link type advertising an XML oEmbed endpoint
const DefaultMaxBodySize = 1 << 20
DefaultMaxBodySize is the default cap (1MB) on response bodies read by the Client — generous for oEmbed documents, which are small, and for the HTML head section that discovery reads.
const FormatJSON = "json"
FormatJSON identifies the JSON oEmbed response format
const FormatXML = "xml"
FormatXML identifies the XML oEmbed response format
const ProvidersSnapshotDate = "2026-08-14"
ProvidersSnapshotDate records when the embedded providers.json snapshot was vendored from oembed.com. Update it whenever the snapshot is regenerated.
const TypeLink = "link"
TypeLink identifies a plain link response with no embeddable content
const TypePhoto = "photo"
TypePhoto identifies a static photo response (requires url, width, height)
const TypeRich = "rich"
TypeRich identifies a rich HTML response (requires html, width, height)
const TypeVideo = "video"
TypeVideo identifies a playable video response (requires html, width, height)
const Version loose.String = "1.0"
Version is the only version of the oEmbed specification, required in every response.
Variables ¶
This section is empty.
Functions ¶
func WriteResponse ¶ added in v0.2.0
func WriteResponse(w http.ResponseWriter, response Response, format string) error
WriteResponse encodes an oEmbed document to an HTTP response in the requested format (FormatJSON, FormatXML, or "" meaning JSON), with the correct Content-Type. The document is validated first — be strict in what you send — so a spec-invalid document is an error, and nothing is written.
Types ¶
type Client ¶ added in v0.2.0
type Client struct {
// contains filtered or unexported fields
}
Client resolves target URLs into validated oEmbed metadata. Construct it with NewClient; the zero-config NewClient() works well, using the embedded provider registry and safe network defaults.
func NewClient ¶ added in v0.2.0
func NewClient(options ...ClientOption) Client
NewClient returns a Client configured by the given options. With no options it uses the embedded provider registry, blocks non-public IP addresses, and caps response bodies at DefaultMaxBodySize.
func (Client) Fetch ¶ added in v0.2.0
Fetch resolves a target URL into validated oEmbed metadata: it tries a provider registry match first (no page fetch needed), falls back to fetching the page and running HTML discovery, calls the resolved endpoint, and validates the parsed response.
func (Client) FetchHTML ¶ added in v0.2.0
func (client Client) FetchHTML(ctx context.Context, pageURL string, header http.Header, reader io.Reader) (Response, error)
FetchHTML resolves an oEmbed response for pageURL using a response the caller already holds, so no page fetch is needed. It behaves exactly like Fetch — provider registry, then the Link header, then the discovery links in the HTML — except that the response comes from the caller instead of the network. pageURL does double duty: relative discovery references resolve against it, and it is the target URL sent to the endpoint.
Pass the response's own header so Link-header discovery works; a nil or empty http.Header is fine and simply skips that step.
This is the whole resolution pipeline in one step, for callers (crawlers, link-preview services) that fetched the page already.
type ClientOption ¶ added in v0.2.0
type ClientOption func(*Client)
ClientOption configures a Client during NewClient.
func WithAllowPrivateIPs ¶ added in v0.2.0
func WithAllowPrivateIPs(allow bool) ClientOption
WithAllowPrivateIPs controls whether fetches may reach non-public IP addresses (loopback, private, link-local). The default is FALSE, which guards against SSRF; set TRUE only for tests against loopback servers or intentional internal calls.
func WithMaxBodySize ¶ added in v0.2.0
func WithMaxBodySize(maxBytes int64) ClientOption
WithMaxBodySize caps how many bytes are read from any response body. Values of zero or less restore DefaultMaxBodySize.
func WithMaxHeight ¶ added in v0.2.0
func WithMaxHeight(maxHeight int) ClientOption
WithMaxHeight sets a default maxheight parameter sent with every endpoint request.
func WithMaxWidth ¶ added in v0.2.0
func WithMaxWidth(maxWidth int) ClientOption
WithMaxWidth sets a default maxwidth parameter sent with every endpoint request.
func WithRegistry ¶ added in v0.2.0
func WithRegistry(registry Registry) ClientOption
WithRegistry replaces the embedded provider registry, for callers that supply a fresher or custom providers.json.
func WithRoundTripper ¶ added in v0.2.0
func WithRoundTripper(wrap func(next http.RoundTripper) http.RoundTripper) ClientOption
WithRoundTripper wraps the SSRF-hardened base transport with caller-supplied middleware (caching, instrumentation, custom headers). The middleware receives the base transport as "next" and must delegate to it; the private-IP guard stays underneath.
func WithUserAgent ¶ added in v0.2.0
func WithUserAgent(userAgent string) ClientOption
WithUserAgent sets the User-Agent header sent with every request.
type Embed ¶ added in v0.2.0
type Embed interface {
// Render returns safe markup for this plan, built from trusted templates
// with full escaping. No caller ever hand-assembles the sandbox attribute.
Render() template.HTML
// contains filtered or unexported methods
}
Embed is a render plan for an oEmbed response — a closed set of ways the response may safely reach a page. Callers switch on the concrete type; raw provider HTML can never escape the classifier unwrapped.
type EmbedIframe ¶ added in v0.2.0
type EmbedIframe struct {
Src string // https iframe source
Width, Height int // player dimensions; zero means unset
Title string // accessible title, when the provider carried one
}
EmbedIframe is the preferred plan: the provider's HTML was exactly one clean iframe, and we rebuilt it ourselves from its attributes.
func (EmbedIframe) Render ¶ added in v0.2.0
func (e EmbedIframe) Render() template.HTML
Render builds the iframe tag from the extracted attributes.
type EmbedLink ¶ added in v0.2.0
type EmbedLink struct {
Title string // link text, falling back to TargetURL when empty
ThumbnailURL string // preview image for the resource, when the provider sent one
TargetURL string // href the anchor points at
}
EmbedLink is the degraded plan: render the response as a plain link — title, thumbnail, anchor.
This is where every other plan falls back to, because a boring preview beats an injected script.
type EmbedPolicy ¶ added in v0.2.0
type EmbedPolicy struct {
// AllowSandbox permits the EmbedSandbox plan: rendering non-extractable
// provider HTML inside a sandboxed srcdoc iframe. FALSE degrades that
// markup to a plain link instead.
//
// This is a UX choice — do script-bearing embeds render at all? — and NOT
// a trust decision about the provider. Note the containment ordering,
// which is the opposite of most people's intuition: EmbedSandbox runs in
// an iframe with a unique opaque origin (no cookies, no storage, no
// parent DOM, no navigation), while EmbedIframe loads the provider's own
// origin with no sandbox at all. Setting this FALSE therefore blocks the
// MORE contained of the two plans; it does not make embedding safer.
AllowSandbox bool
// MaxWidth and MaxHeight clamp plan dimensions. Zero means no clamp.
MaxWidth int // widest dimension a plan may carry
MaxHeight int // tallest dimension a plan may carry
}
EmbedPolicy tells Embed which render plans the caller is willing to display. It is a product decision, not a security ranking: this library never infers policy from how an endpoint was found, and deliberately does not report that provenance.
type EmbedSandbox ¶ added in v0.2.0
type EmbedSandbox struct {
HTML string // provider markup, escaped into srcdoc by Render
Width, Height int // frame dimensions; zero means unset
}
EmbedSandbox is the fallback plan: provider HTML that could not be reduced to a single iframe, rendered only inside a sandboxed srcdoc iframe.
RULE: the sandbox attribute NEVER combines allow-scripts with allow-same-origin — together they let embedded script reach up and rewrite the host page, which un-sandboxes everything.
func (EmbedSandbox) Render ¶ added in v0.2.0
func (e EmbedSandbox) Render() template.HTML
Render wraps the provider HTML in the sandboxed srcdoc iframe.
type Endpoint ¶ added in v0.2.0
type Endpoint struct {
// URL is the concrete endpoint URL to call. It may already carry query
// parameters (discovery links often bake in "url" and "format").
URL string
// Format is the response format this endpoint will produce: FormatJSON or
// FormatXML.
Format string
// AddFormatParameter is TRUE when the request should pass the format as a
// "format" query parameter — set by Registry.Find only when the provider's
// declared formats say the parameter is supported.
AddFormatParameter bool
}
Endpoint is a resolved oEmbed endpoint, ready for request building — found either by registry match (Registry.Find) or by discovery.
type Provider ¶
type Provider struct {
// Name is the human-readable provider name (for example "YouTube")
Name string `json:"provider_name"`
// URL is the provider's home page
URL string `json:"provider_url"`
// Endpoints lists the provider's oEmbed API endpoints
Endpoints []ProviderEndpoint `json:"endpoints"`
}
Provider is one entry in the oEmbed provider registry, mirroring the structure of the official providers.json published at oembed.com.
type ProviderEndpoint ¶
type ProviderEndpoint struct {
// Schemes are wildcard URL patterns (like "https://*.youtube.com/watch*")
// naming the content URLs this endpoint can resolve. An endpoint with no
// schemes is discovery-only and is never scheme-matched.
Schemes []string `json:"schemes"`
// URL is the endpoint address. It may contain a {format} placeholder to be
// replaced with the requested response format.
URL string `json:"url"`
// Discovery is TRUE when the provider supports discovery via
// <link rel="alternate"> elements on its content pages.
Discovery bool `json:"discovery"`
// Formats lists the response formats the endpoint supports ("json",
// "xml"). An empty list makes no promise; JSON is assumed.
Formats []string `json:"formats"`
}
ProviderEndpoint is one oEmbed API endpoint offered by a Provider.
type Registry ¶ added in v0.2.0
type Registry struct {
// contains filtered or unexported fields
}
Registry matches candidate URLs against provider scheme patterns and returns the provider's oEmbed endpoint. Registries are immutable after construction and safe for concurrent use without locks.
func DefaultRegistry ¶ added in v0.2.0
func DefaultRegistry() Registry
DefaultRegistry returns the Registry built from the embedded providers.json snapshot, compiled once at package initialization and shared.
func NewRegistry ¶ added in v0.2.0
NewRegistry builds a Registry from a provider list, precompiling every scheme pattern and pre-resolving every endpoint. Endpoints with no schemes are discovery-only and are never scheme-matched.
func (Registry) Find ¶ added in v0.2.0
Find returns the endpoint of the first provider scheme that matches the candidate URL, in registry order. It reports FALSE when no scheme matches.
Example ¶
registry := DefaultRegistry()
endpoint, found := registry.Find("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
fmt.Println(found, endpoint.Format, endpoint.URL)
Output: true json https://www.youtube.com/oembed
type Response ¶ added in v0.2.0
type Response struct {
// XMLName fixes the XML root element to <oembed>. It is ignored by JSON.
XMLName xml.Name `json:"-" xml:"oembed"`
// Type is the resource type: "photo", "video", "link", or "rich". Required.
Type string `json:"type" xml:"type"`
// Version is the oEmbed version, always "1.0". Required. It is a tolerant
// String because providers send it as a JSON number often enough to matter.
Version loose.String `json:"version" xml:"version"`
// Title is a text title describing the resource. Optional.
Title string `json:"title,omitempty" xml:"title,omitempty"`
// AuthorName is the name of the author/owner of the resource. Optional.
AuthorName string `json:"author_name,omitempty" xml:"author_name,omitempty"`
// AuthorURL is a URL for the author/owner of the resource. Optional.
AuthorURL string `json:"author_url,omitempty" xml:"author_url,omitempty"`
// ProviderName is the name of the resource provider. Optional.
ProviderName string `json:"provider_name,omitempty" xml:"provider_name,omitempty"`
// ProviderURL is the URL of the resource provider. Optional.
ProviderURL string `json:"provider_url,omitempty" xml:"provider_url,omitempty"`
// CacheAge is the suggested cache lifetime for this resource, in seconds. Optional.
CacheAge loose.Int64 `json:"cache_age,omitempty" xml:"cache_age,omitempty"`
// ThumbnailURL is a URL to a thumbnail image representing the resource. If
// any thumbnail field is present, all three must be (enforced by Validate).
ThumbnailURL string `json:"thumbnail_url,omitempty" xml:"thumbnail_url,omitempty"`
// ThumbnailWidth is the width of the thumbnail, in pixels.
ThumbnailWidth loose.Int64 `json:"thumbnail_width,omitempty" xml:"thumbnail_width,omitempty"`
// ThumbnailHeight is the height of the thumbnail, in pixels.
ThumbnailHeight loose.Int64 `json:"thumbnail_height,omitempty" xml:"thumbnail_height,omitempty"`
// URL is the source URL of the image. Required for type "photo".
URL string `json:"url,omitempty" xml:"url,omitempty"`
// HTML is provider-supplied embed markup, required for types "video" and
// "rich". SECURITY: this is arbitrary third-party markup — usually iframe-
// or script-bearing by design — and this library intentionally does NOT
// sanitize it, because stripping scripts and iframes strips the embed.
// Render it only inside a sandboxed iframe or an equivalent CSP boundary;
// never write it directly into your own page.
HTML string `json:"html,omitempty" xml:"html,omitempty"`
// Width is the width in pixels required to display the resource. Required
// for types "photo", "video", and "rich".
Width loose.Int64 `json:"width,omitempty" xml:"width,omitempty"`
// Height is the height in pixels required to display the resource. Required
// for types "photo", "video", and "rich".
Height loose.Int64 `json:"height,omitempty" xml:"height,omitempty"`
}
Response is a single oEmbed response document, covering every parameter in oEmbed 1.0 §2.3.4. It marshals to and from both JSON and XML (root element "oembed"). Provider extension fields are discarded.
func NewLink ¶ added in v0.2.0
NewLink returns a valid-by-construction "link" response: version, type, and title pre-stamped.
func NewPhoto ¶ added in v0.2.0
NewPhoto returns a valid-by-construction "photo" response: version, type, and the required url, width, and height pre-stamped.
func NewResponse ¶ added in v0.2.0
NewResponse returns a Response of the given type with the Version pre-stamped, so a correctly-constructed value cannot be spec-invalid.
Example ¶
response := NewResponse(TypePhoto) response.URL = "https://example.com/photo.jpg" response.Width = 1024 response.Height = 683 fmt.Println(response.Version, response.Type, response.Validate() == nil)
Output: 1.0 photo true
func NewRich ¶ added in v0.2.0
NewRich returns a valid-by-construction "rich" response: version, type, and the required html, width, and height pre-stamped.
func NewVideo ¶ added in v0.2.0
NewVideo returns a valid-by-construction "video" response: version, type, and the required html, width, and height pre-stamped.
func (Response) Embed ¶ added in v0.2.0
func (response Response) Embed(policy EmbedPolicy) Embed
Embed classifies this response into a render plan under the given policy: a rebuilt iframe when the provider HTML is exactly one clean iframe, a sandboxed srcdoc wrapper when policy permits, and a plain link otherwise. The result is always renderable — degradation is the error path.
func (*Response) SetThumbnail ¶ added in v0.2.0
SetThumbnail stamps all three thumbnail fields together, so the spec's all-or-none thumbnail rule cannot be violated piecemeal. An empty url is a no-op: a record without an icon simply has no thumbnail.
func (Response) Validate ¶ added in v0.2.0
Validate confirms that the response satisfies oEmbed 1.0 strictly: a "1.0" version, a known type, that type's required fields, and the all-or-none thumbnail rule. This is the SEND-side check — use it as a backstop before serving a document you authored (be strict in what you send). Received documents go through the Client's more forgiving acceptance instead (be flexible in what you receive).