当前位置: 首页 > 工具软件 > Go template > 使用案例 >

go safe template不转义

井轶
2023-12-01

template显示时默认会转义。编写safe方法可以使内容不被转义。

//template\tmpl转义.tmpl
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {{.msg1}}<br>
    {{.msg2 | safe}}<br>
</body>
</html>
//a1.go
package main

import (
	"html/template"
	"log"
	"net/http"
	// "github.com/gin-gonic/gin"
)

func main() {
	http.HandleFunc("/a2", a2)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Println("HTTP server failed,err:", err)
		return
	}
}

func a2(w http.ResponseWriter, r *http.Request) {
	file := "./template/tmpl转义.tmpl"
	tmpl, err := template.New("tmpl转义.tmpl").
		Funcs(template.FuncMap{"safe": func(s string)template.HTML {
			return template.HTML(s)
		}}).
		ParseFiles(file)
	if err != nil {
		log.Println("create template failed, err:", err)
		return
	}
	Res := map[string]interface{}{
		"msg1": "<script>alert('msg1')</script>",
		"msg2": "<script>alert('msg2')</script>",
	}
	tmpl.Execute(w, Res)
}

访问a2页面,内容是<script>alert('msg1')</script>,并alert(‘msg2’)

 类似资料: