网站首页 > 基础教程 正文
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))
}
执行结果
猜你喜欢
- 2024-11-20 一文搞懂Golang条件判断:if-else语句详解
- 2024-11-20 无需If-Else语句,状态模式即可编写干净可维护的代码
- 2024-11-20 答应我,别再if/else走天下了可以吗
- 2024-11-20 如何对SpringBoot中的IF-ELSE语句进行优化?
- 2024-11-20 道哥说编程--Java流程控制语句if--else详解
- 2024-11-20 if-elif-else,三目运算符,while条件循环,for迭代循环
- 2024-11-20 设计模式:策略模式避免多重分支语句(ifelse)
- 2024-11-20 Excel VBA流程图解之IF语句,多层IF嵌套,其实很简单
- 2024-11-20 4.2 练习编写简单的if语句和else语句
- 2024-11-20 C/C++编程笔记:if—else语句块,有个细节需要注意
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)