github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/03_form/demo03_template.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"html/template"
     6  	"log"
     7  	"net/http"
     8  )
     9  
    10  func login2(w http.ResponseWriter, r *http.Request) {
    11  	r.ParseForm()
    12  
    13  	username := r.Form.Get("username")
    14  	// 防止 XSS Cross Site Scripting  跨站脚本攻击 使用 template.HTMLEscapeString 输出
    15  	fmt.Println("username:", template.HTMLEscapeString(username)) //输出到服务器端
    16  	fmt.Println("password:", template.HTMLEscapeString(r.Form.Get("password")))
    17  	template.HTMLEscape(w, []byte(username)) //输出到客户端
    18  }
    19  
    20  func login3(w http.ResponseWriter, r *http.Request) {
    21  	r.ParseForm()
    22  
    23  	username := r.Form.Get("username")
    24  	fmt.Printf(username)
    25  	t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
    26  	//err = t.ExecuteTemplate(w, "T", username)
    27  	err = t.ExecuteTemplate(w, "T", template.HTML(username))
    28  
    29  	//如果转义失败 抛出对应错误 终止程序
    30  	if err != nil {
    31  		log.Fatal(err)
    32  	}
    33  
    34  }
    35  func main() {
    36  	http.HandleFunc("/login2", login2)
    37  	http.HandleFunc("/login3", login3)
    38  	err := http.ListenAndServe(":8000", nil) //设置监听的端口
    39  	if err != nil {
    40  		log.Fatal("ListenAndServe: ", err)
    41  	}
    42  }