Goのhtml/templateでURLをエンコードさせない

Goのhtml/templateでURLをエンコードさせない

Read in: en
Goのhtml/templateでURLをエンコードさせない

概要

html/templateを使っているときに、テンプレートに渡すURLをエンコードさせたくなかった。

template.URLを使う

Goのhtml/templateを使って、URLをテンプレートに渡すとエンコードされてしまう仕様になっている。

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

セキュリティ上の理由でこのような仕様になっていると思うが、HTML上でこれを回避したいようなケースがあると思う。

そういうときはtemplate.URLを使うと回避できる。

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

所感

地味にハマった。

Tags: Golang Tips
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ サポート

このブログを応援していただける方は、以下からサポートをお願いします。いただいたサポートはブログ運営・技術研鑽に活用します。


関連記事