Resolve Relative URLs With ResolveReference

Turn relative links into absolute ones by resolving each against a base URL: path-only, root-relative, fragment-only, and dot-segment forms all resolve.

GoData Fetching

Code

gosnippet
22 lines
package main

import (
	"fmt"
	"net/url"
)

func main() {
	base, err := url.Parse("https://devexamples.com/docs/guide/page.html")
	if err != nil {
		panic(err)
	}

	// 四种相对形态:同目录、根路径、纯锚点、带 .. 的段
	for _, ref := range []string{"next.html", "/api/v1", "#section-2", "chap/../intro.html"} {
		parsed, err := url.Parse(ref)
		if err != nil {
			panic(err)
		}
		fmt.Printf("%-18s -> %s\n", ref, base.ResolveReference(parsed))
	}
}

Four relative shapes, one base

The loop parses each reference and resolves it against base = https://devexamples.com/docs/guide/page.html via base.ResolveReference(parsed), printing with fmt.Printf("%-18s -> %s\n", ref, …). The four shapes cover the cases a crawler or link fixer meets in real pages: a sibling path, a root-relative path, a bare fragment, and a path with dot segments.

What each reference becomes

next.html         -> https://devexamples.com/docs/guide/next.html
/api/v1           -> https://devexamples.com/api/v1
#section-2        -> https://devexamples.com/docs/guide/page.html#section-2
chap/../intro.html -> https://devexamples.com/docs/guide/intro.html

A path-only reference stays in the base’s directory (/docs/guide/next.html); a leading / resets to the host root (/api/v1); a fragment-only reference keeps the base path and only changes the fragment; and chap/../intro.html collapses its dot segment inside the base directory, never touching the base’s own file name.

The line that fails fast

parsed, err := url.Parse(ref)
if err != nil {
	panic(err)
}

Both parse calls (base and per-reference) abort on error rather than resolving a garbage URL — with fixed literals here, that arm exists for the adapted version, where refs come from untrusted input.

Interactive Tools for This Topic

FAQ

What is the error handling style?
The failure path is `panic(err)` — detected problems halt the run rather than being passed back.
How do you run Resolve Relative URLs With ResolveReference?
This is a complete program, not a library excerpt — execution starts at the top.