技術向上

プログラミングの学び、気になるテクノロジーやビジネストレンドを発信

html/templateとtext/template【Go】

html/templateは、text/templateの拡張版です。
text/templateの全ての機能を、html/templateは備えています。
それに加えて、htmlに必要な機能を併せ持っています。

例えば文字エスケープです。XSS対策になります。

main.goです。
text/templateをimportした場合、下記内容ですとXSSの発生する余地が残ってしまいます。
html関連のことを処理するならば、html/templateをimportすべきです。

import (
    "log"
    "os"
    "text/template"    // textの場合、エスケープがされない
)

var tpl *template.Template

type Content struct {
    Name string
    Do   string
}

func init() {
    tpl = template.Must(template.ParseGlob("templates/*"))
}

func main() {
    nf, err := os.Create("index.html")
    if err != nil {
        log.Fatal(err)
    }
    c := &Content{Name: "Scripting!", Do: `<script>alert("Boom!")</script>`}    // エスケープされない場合、アラートが発動される
    err = tpl.ExecuteTemplate(nf, "tpl.gohtml", c)
    if err != nil {
        log.Fatalln(err)
    }
}


tpl.gohtmlです。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
    <h1>{{.Name}}</h1>
    {{.Do}}    // ここを読み込んだ時に、エスケープされていない場合、alertが発生する
</body>
</html>


生成されたindex.htmlをブラウザ上で開くと、alertが発生します。
html/templateをimportした場合は、alertは発生しません。