golang从入门到精通,模板内置函数自定义函数管道符的使用
这篇文章将学习模板内置函数的使用、自定义函数的使用、管道符的使用D:gosrcgo7demo1main.go源码及解析//本节将学习模板内置函数的使用、自定义函数的使用、管道符的使用 package main import ( "net/http" "text/template" "time" ) // TimeToString 声明TimeToString函数,将time.Time转换成"2006-01-02 15:04:05"格式的字符串 func TimeToString(time time.Time) string { return time.Format("2006-01-02 15:04:05") } func Add(int1 int) int { return int1 + 1 } func Index(w http.ResponseWriter, r *http.Request) { // FuncMap:定义从名称到函数的映射的一一映射。 // time_to_String是定义的名称,TimeToString是执行的函数 funcMap := template.FuncMap{ "time_to_String": TimeToString, "int_add_1": Add, } //New:给名称funcMap分配一个新的、未定义的模板t。 t := template.New("index.html").Funcs(funcMap) //func ParseFiles(filenames ...string) (*Template, error) //ParseFiles从"index.html"中解析模板。 //如果发生错误,解析停止,返回的*Template为nil。 //当解析多个文件时,如果文件分布在不同目录中,且具有相同名字的,将以最后一个文件为主。 //当解析多个文件时,如果文件分布在相同目录中,且具有不同名字的,将以第一个文件为主。 files, _ := t.ParseFiles("index.html", "home.html") //渲染模板文件,并将定义的map类型的数据传入模板文件中 //由于采用的Execute方法,那么渲染的模板应当遵循template.ParseFiles的解析顺序 _ = files.Execute(w, map[string]interface{}{ "score": 18.5, "year": []int{2018, 2019, 2020, 2021, 2022}, "str1": "golang 从入门到精通", //将当前时间输出到模板 "ctime": time.Now(), //输出到模板1个int数据 "int1": 18, }) } func main() { http.HandleFunc("/", Index) _ = http.ListenAndServe(":80", nil) }D:gosrcgo7demo1index.html源码及解析 index index.html
使用管道符号进行处理 score,保留小数点后2位 : {{.score | printf "%.2f"}} 使用函数进行处理 score,保留小数点后2位: : {{printf "%.2f" .score}} 使用index函数获取[]string内值 : {{index .year 1}} 使用len函数获取string长度 : {{index .str1 1}} 使用println函数输出字符串(带换行) : {{println .str1}} 使用printf函数输出字符串和类型 : {{printf "str1的值是:%v , 类型是: %T" .str1 .str1}} 使用自定义函数time_to_String格式化输出当前时间.ctime : {{time_to_String .ctime}} 使用自定义函数int_add_1处理.int1 : 当前是:{{.int1}} 执行函数后是:{{int_add_1 .int1}}
执行结果:=== RUN TestIndex main_test.go:15: http://127.0.0.1:50010/index main_test.go:19: index index.html
使用管道符号进行处理 score,保留小数点后2位 : 18.50 使用函数进行处理 score,保留小数点后2位: : 18.50 使用index函数获取[]string内值 : 2019 使用len函数获取string长度 : 111 使用println函数输出字符串(带换行) : golang 从入门到精通 使用printf函数输出字符串和类型 : str1的值是:golang 从入门到精通 , 类型是: string 使用自定义函数time_to_String格式化输出当前时间.ctime : 2022-01-06 18:08:10 使用自定义函数int_add_1处理.int1 : 当前是:18 执行函数后是:19
--- PASS: TestIndex (0.02s) PASS
执行结果是通过单元测试得到的,当然也可以直接进行go run .启动web服务,通过浏览器URL进行查看。下面是单元测试的源码package main import ( "io/ioutil" "net/http" "net/http/httptest" "testing" ) func TestIndex(t *testing.T) { handler := http.HandlerFunc(Index) app := httptest.NewServer(handler) defer app.Close() _url := app.URL + "/" + "index" t.Log(_url) response, _ := http.Get(_url) defer response.Body.Close() bytes, _ := ioutil.ReadAll(response.Body) t.Log(string(bytes)) }