G01學習筆記-3

zcold發表於2021-05-16

閱讀位置 5.5

知識點

1、中介軟體

func forceHTMLMiddleware(next http.Handler) http.Handler {
   return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
      // todo something

      // 繼續處理請求
      next.ServeHTTP(w, r)
   })
}

mux.NewRouter().Use(mwf ...MiddlewareFunc)

2、/ 問題

因為mux路由是 精準匹配 ,請求地址後面帶 / 會導致404
mux.NewRouter().StrictSlash(true) 可以解決,但是是通過重定向的方式,不符合實際需求

最終通過重寫請求地址

func removeTrailingSlash(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.URL.Path != "/"{
            r.URL.Path = strings.TrimSuffix(r.URL.Path, "/")
        }
        next.ServeHTTP(w, r)
    })
}

func main(){
    .
    .
    .
    http.ListenAndServe(":3000", removeTrailingSlash(router))
}

3、表單引數接收

以下 r 為 http.Request

  • 獲取全部引數值,獲取前必須執行 r.ParseForm()
    r.PostForm: 儲存了 post、put 引數
    r.Form: 儲存 post、put 和 get 引數

  • 獲取單個欄位值,可不使用r.ParseForm()
    r.FormValue("field")
    r.PostFormValue("field")

4、len驗證中文長度問題

Go 語言的字串都以 UTF-8 格式儲存,每個中文佔用 3 個位元組,因此使用 len () 獲得一箇中文文字對應的 3 個位元組

通過 utf8.RuneCountInString() 函式來計數

5、標準包 html/template

使用基礎

tmpl, err := template.ParseFiles("filePath")
tmpl.Execute(w, data)

基本語法

  • {{ . }} 中的點表示當前物件。當我們傳入一個結構體物件時,可以使用 . 來訪問結構體的對應欄位
  • {{- .Name -}}移除空格
  • 條件判斷
    {{if pipeline}} T1 {{end}}
    {{if pipeline}} T1 {{else}} T0 {{end}}
    {{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
  • range
    //如果pipeline的值其長度為0,不會有任何輸出
    {{range pipeline}} T1 {{end}}
    //如果pipeline的值其長度為0,則會執行T0
    {{range pipeline}} T1 {{else}} T0 {{end}}
  • with
    //如果pipeline為empty不產生輸出,否則將dot設為pipeline的值並執行T1。不修改外面的dot。
    {{with pipeline}} T1 {{end}}
    //如果pipeline為empty,不改變dot並執行T0,否則dot設為pipeline的值並執行T1。
    {{with pipeline}} T1 {{else}} T0 {{end}}
  • 比較函式
    /**
    eq      如果arg1 == arg2則返回真
    ne      如果arg1 != arg2則返回真
    lt      如果arg1 < arg2則返回真
    le      如果arg1 <= arg2則返回真
    gt      如果arg1 > arg2則返回真
    ge      如果arg1 >= arg2則返回真*/
    {{eq arg1 arg2 arg3}}

/html/template 官方: golang.org/pkg/html/template/
/html/template 本教程:G01 html/template

  • 貴在堅持,自我驅動,go 小白在成長
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章