G01学习笔记-3

阅读位置 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 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!