Application 2023-04-23

Prevent URL Encoding in Go's html/template

Learn why Go html/template auto-encodes URLs and how to use template.URL to pass raw URLs in templates without triggering automatic HTML encoding. Includes a minimal working example.

Read in: ja
Prevent URL Encoding in Go's html/template

Overview

When using html/template, I wanted to prevent the URL passed to the template from being encoded.

Using template.URL

When you use Go's html/template to pass a URL to a template, it is designed to be encoded.

cf. https://pkg.go.dev/html/template#hdr-Contexts

I believe this is due to security reasons, but there might be cases where you want to avoid this in HTML.

In such cases, you can use template.URL to avoid it.

package main

import (
	"html/template"
	"os"
)

func main() {
	const tpl = `
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>bmf-tech.com</title>
	</head>
	<body>
		<a href="{{ .URL }}">bmf-tech.com</a>
	</body>
</html>`

	t, _ := template.New("index").Parse(tpl)
	data := struct {
		URL template.URL
	}{
		URL: template.URL("http://bmf-tech/posts/search?keyword=something"),
	}

	t.Execute(os.Stdout, data)
}

Thoughts

I got stuck on this unexpectedly.

Tags: Golang Tips
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles