详细代码git
package main
import (
"github.com/gin-gonic/gin"
"html/template"
"log"
"net/http"
)
func main() {
mainGin()
}
func mainGin() {
r := gin.Default()
r.Static("/cssjs","./static")
r.SetFuncMap(template.FuncMap{
"safe": func(s string) template.HTML {
return template.HTML(s)
},
"sqr": func(i int) int {
return i * i
},
})
r.LoadHTMLFiles(
"./template/tmpl转义.html",
"./template/tmpl基本语法.go.tmpl",
"./template/test1/block.tmpl",
"./template/test1/useblock.tmpl",
"./template/test1/js.html")
r.GET("/a1", func(c *gin.Context) {
c.HTML(http.StatusOK, "useblock.tmpl", nil)
})
r.GET("/a2", func(c *gin.Context) {
c.HTML(http.StatusOK, "tmpl转义.html", gin.H{
"msg1": "<script>alert('msg1')</script>",
"msg2": "<script>alert('msg2')</script>",
})
})
r.GET("/j1", func(c *gin.Context) {
c.JSON(http.StatusOK,gin.H{
"name":"kitty",
"age":3,
})
})
r.GET("/j2", func(c *gin.Context) {
type user struct{
Name string `json:"usernane"`
age int8
Weight float32
}
u:=user{"kitty2",4,1.23}
c.JSON(http.StatusOK,u)
})
r.Run(":8080")
}
//template\tmpl转义.html
<!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>
<link rel="stylesheet" href="/cssjs/css/a.css">
<script src="/cssjs/js/jquery.min.js"></script>
</head>
<body>
<div class='a'>aaaa</div>
{{.msg1}}<br>
{{.msg2 | safe}}<br>
</body>
</html>