Validate Redirects With URL.ResolveReference
Resolve relative, protocol-relative, and external redirect strings against a base net/url.URL, then enforce same-scheme and same-host checks.
Code
package main
import (
"fmt"
"net/url"
)
func safeRedirect(base *url.URL, rawTarget string) (string, bool) {
ref, err := url.Parse(rawTarget)
if err != nil {
return "", false
}
resolved := base.ResolveReference(ref)
sameOrigin := resolved.Scheme == base.Scheme && resolved.Host == base.Host
return resolved.String(), sameOrigin
}
func main() {
base, err := url.Parse("https://app.example.org/account/profile")
if err != nil {
fmt.Println("invalid base:", err)
return
}
targets := []string{
"settings",
"/billing?plan=pro",
"//evil.example.net/steal",
"https://other.example.org/login",
}
for _, target := range targets {
dest, ok := safeRedirect(base, target)
fmt.Printf("%-32s allowed=%-5t resolved=%s\n", target, ok, dest)
}
}Code mechanics — Validate Redirects With URL.ResolveReference
Inspect the flow starting from routines safeRedirect and main, doing all the work.
The cycling part of this snippet is for _, target := range targets. Error handling is inline: 2 places test err != nil and branch immediately.
What to watch for
- Only the core language runtime is required — zero third-party installs.
Applying it
The entry-point signature is func safeRedirect(base *url.URL, rawTarget string) (string, bool)
The run prints invalid base: — each prefix names the step that produced it.
Launch the file; main takes over and steps through safeRedirect.
Statements that matter
func safeRedirect(base *url.URL, rawTarget string) (string, bool) {
ref, err := url.Parse(rawTarget)
if err != nil {
return "", false
}
resolved := base.ResolveReference(ref)
sameOrigin := resolved.Scheme == base.Scheme && resolved.Host == base.Host
return resolved.String(), sameOrigin
}
for _, target := range targets {
dest, ok := safeRedirect(base, target)
fmt.Printf("%-32s allowed=%-5t resolved=%s\n", target, ok, dest)
}
if err != nil {
fmt.Println("invalid base:", err)
return
}
Interactive Tools for This Topic
URL Safety CheckerEvaluate a URL against common phishing red flags such as plain HTTP, embedded credentials, IP hosts, Punycode, and risky top-level domains.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- What does Validate Redirects With URL.ResolveReference print when run?
- Invoke the file as-is — the `invalid base:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.