编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Golang Web编程,模板解析 if、else if、else语句

wxchong 2024-11-11 14:36:21 开源技术 60 ℃ 0 评论

if、else if、else语句

main.go源码及解析

package main

import (
	"math/rand"
	"net/http"
	"text/template"
	"time"
)

func main() {
	server := http.Server{
		Addr: ":80",
	}
	http.HandleFunc("/index", Index)
	_ = server.ListenAndServe()
}
func Index(w http.ResponseWriter, r *http.Request) {
	//template.ParseFiles解析"index.html"模板
	files, _ := template.ParseFiles("index.html")
	//生成随机数种子
	rand.Seed(time.Now().Unix())
	//Execute渲染模板,并传入一个随机数rand.Intn(100)
	_ = files.ExecuteTemplate(w, "index.html", rand.Intn(100))
}

模板index.html的源码及解析

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<pre>
{{/*    输出传递进来的值*/}}
    {{.}}
    {{/*    传递进来的值与50比较,eq检测是否相等*/}}
    {{eq . 50}}
    {{/*    传递进来的值与50比较,lt检测是否小于50*/}}
    {{lt . 50}}
    {{/*    传递进来的值与50比较,gt检测是否大于50*/}}
    {{gt . 50}}
    {{/*    判断语句,如果传递进来的值等于50*/}}
    {{if eq . 50}}
        {{/*        显示= 50*/}}
        {{.}} = 50
        {{/*    判断语句,如果传递进来的值不等于50,且小于50*/}}
    {{else if lt . 50}}
        {{/*        显示< 50*/}}
        {{.}} < 50
        {{/*    判断语句,如果传递进来的值不等于50,不小于50,且大于50*/}}
    {{else if gt . 50}}
        {{/*        显示> 50*/}}
        {{.}} > 50
        {{/*    判断语句,如果上面的条件都不成立*/}}
    {{else}}
        {{/*        那么显示none*/}}
        none
    {{end}}
</pre>
</body>
</html>

测试http服务,推荐使用httptest进行单元测试

package main

import (
   "io/ioutil"
   "net/http"
   "net/http/httptest"
   "testing"
)

func TestIndexGet(t *testing.T) {
   //初始化测试服务器
   handler := http.HandlerFunc(Index)
   app := httptest.NewServer(handler)
   defer app.Close()
   //测试代码
   //发送http.Get请求,获取请求结果response
   response, _ := http.Get(app.URL + "/index")
   //关闭response.Body
   defer response.Body.Close()
   //读取response.Body内容,返回字节集内容
   bytes, _ := ioutil.ReadAll(response.Body)
   //将返回的字节集内容通过string()转换成字符串,并显示到日志当中
   t.Log(string(bytes))
}

执行结果

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表