oembed

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

🖼️ oEmbed

Go Reference Version Build Status Go Report Card Codecov

The Careful oEmbed Client for Go

oembed turns a URL into validated metadata — the title, author, thumbnail, and embeddable HTML that providers like YouTube, Vimeo, Flickr, and Mastodon publish for their content. It resolves endpoints, tolerates what providers actually send, and treats their markup as the untrusted input it is.

Everything meets at one type, oembed.Response — the spec's response document, in memory.

This README is the tour; API.md is the full reference for every exported symbol.

Client

Give it a URL. It resolves the endpoint against the embedded provider registry first (zero page fetches on a hit), then fetches the page and looks for an advertised endpoint — first in the HTTP Link header, then by stream-parsing the <head> for <link rel="alternate" type="application/json+oembed"> tags. Then it calls the endpoint and hands back a checked Response.

// Zero configuration: embedded registry, SSRF guard on, 1MB body cap
client := oembed.NewClient()

// Fetch resolves the URL (registry first, discovery fallback),
// calls the endpoint, and validates the response
response, err := client.Fetch(ctx, "https://www.youtube.com/watch?v=dQw4w9WgXcQ")
if err != nil {
    return err
}

fmt.Println(response.Title, response.AuthorName, response.ThumbnailURL)

Already have the response in hand? FetchHTML runs the same pipeline against what you supply instead of the network:

// Same result as Fetch, minus the page request you already made
response, err := client.FetchHTML(ctx, pageURL, header, bytes.NewReader(pageBody))

Pass the response's own http.Header so Link-header discovery works — a nil header is fine and simply skips that step, which is what mocks and tests usually want.

Discovery tolerates truncated, misnested, and outright hostile HTML, and stops at </head> rather than reading megabytes of body. When no endpoint can be found at all, the error reports as not-found.

Fetch and FetchHTML are the whole client. The intermediate steps — header parsing, HTML discovery, calling a resolved endpoint — are unexported, so there is one way to fetch and no way to assemble a half-guarded pipeline by hand.

NewClient takes functional options, and the zero-configuration NewClient() is a sane client on its own:

Option Default What it does
WithRegistry(registry) embedded snapshot Resolve providers against your own registry instead of the vendored providers.json — a fresher snapshot, or a private list.
WithMaxWidth(pixels) unset Send maxwidth with every endpoint request, asking providers to size embeds and thumbnails to fit. Zero omits the parameter.
WithMaxHeight(pixels) unset Send maxheight with every endpoint request. Zero omits the parameter.
WithMaxBodySize(bytes) 1 MB Cap how many bytes are read from any response body, page or endpoint. Zero or less restores the default.
WithAllowPrivateIPs(bool) false Permit fetches to non-public addresses. Leave this off in production — it is the SSRF guard. Turn it on for tests against loopback servers.
WithUserAgent(string) oembed-client/1.0 (+…) Identify yourself to providers. Some rate-limit or block unfamiliar agents, so set this to something you own.
WithRoundTripper(wrap) none Wrap the guarded transport with your own middleware for caching, instrumentation, or extra headers. Your wrapper receives the base transport as next and must delegate to it; the private-IP guard stays underneath.

Authoring a Response

This is a client library, so serving oEmbed is not its job — there is no request parser and no endpoint advertiser. What it does carry is the response document, because that is the same type either way, and writing one correctly is easy to get wrong.

// Version and type are pre-stamped, so the document can't be spec-invalid
response := oembed.NewLink("My Page Title")
response.ProviderName = "My Site"

// All three thumbnail values move together, or none do
response.SetThumbnail("https://example.com/thumb.png", 600, 400)

// Validate, encode, and set the right Content-Type in one call
err := oembed.WriteResponse(w, response, oembed.FormatJSON)

NewLink, NewPhoto, NewVideo, and NewRich stamp the version and type so a document can't be spec-invalid by construction, and SetThumbnail takes all three thumbnail values together so the spec's all-or-none rule can't be broken piecemeal. WriteResponse validates before it writes: an invalid document is an error with nothing on the wire, never a half-written response.

Registry

An embedded snapshot of the official providers.json (369 providers, 838 URL patterns) compiles into fast matchers at startup and is indexed by host, so the common case — a YouTube or Vimeo link — resolves in microseconds with zero page fetches. Wildcard schemes (https://*.youtube.com/watch*), {format} substitution, and format negotiation all work as the registry intends. Registries are immutable after construction and safe for concurrent use with no locks.

The registry earns its keep: Vimeo, Spotify, TikTok, Reddit, GIPHY, Dailymotion, and Instagram serve no discovery links in their HTML, so discovery alone cannot resolve them.

The snapshot refreshes at build time only — the library never fetches it over the network on its own:

$ go generate ./...   # re-downloads providers.json from oembed.com

Then update ProvidersSnapshotDate to match the day you pulled it. Callers who need a fresher or private list can supply their own:

client := oembed.NewClient(oembed.WithRegistry(oembed.NewRegistry(providers)))

Security

Outbound requests are guarded by default. Every fetch goes through benpate/remote's SSRF protection: non-public addresses (loopback, private ranges, cloud metadata IPs) are refused unless you explicitly opt in with WithAllowPrivateIPs(true), and the check lives in the transport dialer, so it re-runs on every redirect hop and survives DNS rebinding. Response bodies are capped at 1MB by default, redirects are bounded, and endpoints must be http(s) — javascript:, data:, and friends are dropped wherever a URL enters, including hrefs found during discovery.

Content types are refused, never sniffed. A response whose Content-Type contradicts the format we asked for is rejected rather than guessed at.

The HTML field is a trust boundary. It is arbitrary, provider-controlled markup — usually iframe- or script-bearing by design — and this library intentionally does not sanitize it, because stripping the scripts and iframes strips the embed. Writing response.HTML into your own page hands your DOM to a third party you discovered at runtime. Never do that; use the Embed() classifier, which turns a response into one of three render plans and never lets raw provider markup escape unwrapped:

policy := oembed.EmbedPolicy{
    AllowSandbox: siteAllowsScriptEmbeds, // your UX call, applied to every provider alike
    MaxWidth:     800,
    MaxHeight:    600,
}

switch plan := response.Embed(policy).(type) {
case oembed.EmbedIframe:  // provider HTML was exactly one clean https iframe — rebuilt by us
    page.Write(plan.Render())
case oembed.EmbedSandbox: // messier markup, wrapped in <iframe sandbox srcdoc="...">
    page.Write(plan.Render())
case oembed.EmbedLink:    // everything else degrades to a plain anchor
    page.Write(plan.Render())
}

The three strategies, in descending order of safety:

  1. Extract — when HTML is exactly one <iframe> (whitespace aside) with an https src, no srcdoc, and no event handlers, the iframe is rebuilt from an attribute allowlist. The provider's content then runs on the provider's origin, isolated by the browser's own cross-origin rules; their markup never enters your page.
  2. Sandbox — when policy permits (AllowSandbox), the markup renders inside <iframe sandbox="allow-scripts allow-popups" srcdoc="...">. The sandbox attribute is baked into a constant template so no caller can add allow-same-origin, which combined with allow-scripts would let the embed reach up and rewrite the host page.
  3. Degrade — everything else becomes a plain link, because a boring preview beats an injected script.

AllowSandbox is a product decision, not a trust ranking — do script-bearing embeds render at all on your site? — and this library never infers it from how the endpoint was found. Note the containment ordering before you reach for it, because it inverts 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. Turning AllowSandbox off blocks the more contained of the two plans; it does not make embedding safer.

Your page's own CSP remains the outer wall — frame-src should allow the player hosts you expect and nothing else. A strict script-src matters too: srcdoc iframes inherit the embedding page's CSP, so a strict policy blocks inline script inside a sandboxed embed entirely.

Other

Strict on send, liberal on receive

Providers infamously send "width": "480" as a string, floats where integers belong, null heights for auto-sized embeds, and — in SoundCloud's case — "version": 1.0 as a JSON number. Two tolerant field types from rosetta/loose absorb all of it: loose.Int64 for the dimensions and loose.String for the version, which keeps a number's exact source text so 1.0 stays "1.0". Received documents are then accepted whenever their essential payload is usable; a missing dimension simply means "auto". Response.Validate() stays the strict spec check for documents you author, so tolerance never leaks into what you publish.

Formats

Both JSON and XML round-trip in both directions (XML root element <oembed>), through the standard library's default encoders. Provider extension fields — Flickr's flickr_type, Vimeo's duration — are discarded rather than retained.

Credits

Portions of this code are inspired or duplicated from:

No Warranty

This software is provided as-is, without any warranty of any kind. Use it at your own risk.

Pull Requests Welcome

I'm trying to make oembed the best it can be, and your help is greatly appreciated. If you find a bug or have an idea for a new feature, please open an issue or submit a pull request. We're all in this together! 🖼️

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

Examples

Constants

View Source
const ContentTypeJSONOEmbed = "application/json+oembed"

ContentTypeJSONOEmbed is the link type advertising a JSON oEmbed endpoint

View Source
const ContentTypeXMLOEmbed = "text/xml+oembed"

ContentTypeXMLOEmbed is the link type advertising an XML oEmbed endpoint

View Source
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.

View Source
const FormatJSON = "json"

FormatJSON identifies the JSON oEmbed response format

View Source
const FormatXML = "xml"

FormatXML identifies the XML oEmbed response format

View Source
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.

View Source
const TypeLink = "link"

TypeLink identifies a plain link response with no embeddable content

View Source
const TypePhoto = "photo"

TypePhoto identifies a static photo response (requires url, width, height)

View Source
const TypeRich = "rich"

TypeRich identifies a rich HTML response (requires html, width, height)

View Source
const TypeVideo = "video"

TypeVideo identifies a playable video response (requires html, width, height)

View Source
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

func (client Client) Fetch(ctx context.Context, targetURL string) (Response, error)

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 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.

func (EmbedLink) Render added in v0.2.0

func (e EmbedLink) Render() template.HTML

Render emits the plain-link fallback.

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

func NewRegistry(providers []Provider) Registry

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

func (registry Registry) Find(targetURL string) (Endpoint, bool)

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

func (Registry) Size added in v0.2.0

func (registry Registry) Size() int

Size returns the number of precompiled scheme matchers in this Registry.

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(title string) Response

NewLink returns a valid-by-construction "link" response: version, type, and title pre-stamped.

func NewPhoto added in v0.2.0

func NewPhoto(url string, width int, height int) Response

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

func NewResponse(oembedType string) Response

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

func NewRich(html string, width int, height int) Response

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

func NewVideo(html string, width int, height int) Response

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

func (response *Response) SetThumbnail(url string, width int, height int)

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

func (response Response) Validate() error

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).

Jump to

Keyboard shortcuts

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