or rang语句 :实现遍历数据功能,可以实现对数组、Slice、Map、或Channel等数据结构
. 表示每次迭代循环中的元素
main.go源码及解析
package main
import (
"net/http"
"text/template"
)
func Index(w http.ResponseWriter, r *http.Request) {
//ParseFiles从"index.html"中解析模板。
//如果发生错误,解析停止,返回的*Template为nil。
//当解析多个文件时,如果文件分布在不同目录中,且具有相同名字的,将以最后一个文件为主。
files, _ := template.ParseFiles("index.html")
//声明变量b,类型为字符串切片,有三个内容
b := []string{"张无忌", "张三丰", "张翠山"}
//声明变量b,类型为字符串切片,没有内容,是为了else示例
//b := []string{}
//Execute负责渲染模板,并将b写入模板。
_ = files.Execute(w, b)
//w.Write([]byte("/index"))
}
func main() {
http.HandleFunc("/index", Index)
_ = http.ListenAndServe("", nil)
}
模板index.html的源码及解析
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<pre>
{{range .}}
{{.}}
{{else}}
None
{{end}}
</pre>
</body>
</html>
测试http服务,推荐使用httptest进行单元测试
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()
//测试代码
//发送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))
}
执行结果
ain.go
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)
//加载首页的页面
func indexHandler(w http.ResponseWriter, r *http.Request) {
data, err := ioutil.ReadFile("./static/index.html")
if err != nil {
io.WriteString(w, "internel server error")
return
}
io.WriteString(w, string(data))
//w.Write(data)
}
//接收表单参数
func userHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析参数,默认是不会解析的
if r.Method == "GET" { //GET请求的方法
username := r.Form.Get("username") //必须使用双引号, 注意: 这里的Get 不是指只接收GET请求的参数, 而是获取参数
password := r.Form.Get("password")
//limit, _ := strconv.Atoi(r.Form.Get("limit")) //字符串转整数的接收方法
//io.WriteString(w, username+":"+password)
w.Write([]byte(username + ":" + password))
} else if r.Method == "POST" { //POST请求的方法
username := r.Form.Get("username") //必须使用双引号, 注意: POST请求, 也是用Get方法来接收
password := r.Form.Get("password")
//io.WriteString(w, username+":"+password)
w.Write([]byte(username + ":" + password))
}
}
//文件上传
func uploadHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //解析参数,默认是不会解析的
if r.Method == "GET" { //GET请求的方法
data, err := ioutil.ReadFile("./static/upload.html")
if err != nil {
io.WriteString(w, "internel server error")
return
}
io.WriteString(w, string(data))
} else if r.Method == "POST" { //POST请求的方法
// 接收文件流及存储到本地目录
file, head, err := r.FormFile("image") //接收文件域的方法
if err != nil {
fmt.Printf("Failed to get data, err:%s\n", err.Error())
return
}
defer file.Close()
newFile, err := os.Create("C:/tmp/" + head.Filename) //创建文件
if err != nil {
fmt.Printf("Failed to create file, err:%s\n", err.Error())
return
}
defer newFile.Close()
FileSize, err := io.Copy(newFile, file) //拷贝文件
if err != nil {
fmt.Printf("Failed to save data into file, err:%s\n", err.Error())
//http.Redirect(w, r, "/static/index.html", http.StatusFound) //重定向的方法
return
}
io.WriteString(w, "上传成功"+strconv.FormatInt(FileSize, 10)) //int64转换成string
}
}
func main() {
// 静态资源处理
http.Handle("/static/",
http.StripPrefix("/static/",
http.FileServer(http.Dir("./static"))))
// 动态接口路由设置
http.HandleFunc("/index", indexHandler)
http.HandleFunc("/user", userHandler)
http.HandleFunc("/upload", uploadHandler)
// 监听端口
fmt.Println("上传服务正在启动, 监听端口:8080...")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Printf("Failed to start server, err:%s", err.Error())
}
}
static/upload.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="image" value="upload" />
<input type="submit" value="上传"/>
</form>
</body>
</html>
static/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>这是首页的内容</p>
</body>
</html>
D:\work\src>go run main.go
上传服务正在启动, 监听端口:8080...
访问方式:
http://localhost:8080/upload
么是设计模式?
设计模式是一套理论, 由软件界先辈们总结出的一套可以反复使用的经验, 可以提高代码可重用性, 增强系统可维护性, 以及巧妙解决一系列逻辑复杂的问题(运用套路).
1995 年,艾瑞克·伽马(ErichGamma)、理査德·海尔姆(Richard Helm)、拉尔夫·约翰森(Ralph Johnson)、约翰·威利斯迪斯(John Vlissides)等 4 位作者合作出版了《设计模式:可复用面向对象软件的基础》(Design Patterns: Elements of Reusable Object-Oriented Software)一书,在本教程中收录了 23 个设计模式,这是设计模式领域里程碑的事件,导致了软件设计模式的突破。这 4 位作者在软件开发领域里也以他们的“四人组”(Gang of Four,GoF)匿名著称.
Go 语言设计模式的实例代码 + 代码图解
项目地址:https://github.com/ssbandjl/golang-design-pattern
简单工厂模式(Simple Factory)
工厂方法模式(Factory Method)
抽象工厂模式(Abstract Factory)
创建者模式(Builder)
原型模式(Prototype)
单例模式(Singleton)
适配器模式(Adapter)
享元模式(Flyweight)
装饰模式(Decorator)
参考文档
廖雪峰:
https://www.liaoxuefeng.com/wiki/1252599548343744/1281319417937953
图解设计模式: http://c.biancheng.net/view/1397.html
golang-design-patttern: https://github.com/senghoo/golang-design-pattern
END已结束
欢迎大家留言, 订阅, 交流哦!
往期回顾
[翻译自官方]什么是RDB和AOF? 一文了解Redis持久化!
Golang GinWeb框架9-编译模板/自定义结构体绑定/http2/操作Cookie/完结
Golang GinWeb框架8-重定向/自定义中间件/认证/HTTPS支持/优雅重启等
Golang GinWeb框架7-静态文件/模板渲染
Golang GinWeb框架6-XML/JSON/YAML/ProtoBuf等渲染
Golang GinWeb框架5-绑定请求字符串/URI/请求头/复选框/表单类型
Golang GinWeb框架4-请求参数绑定和验证
Golang GinWeb框架3-自定义日志格式和输出方式/启禁日志颜色
Golang GinWeb框架2-文件上传/程序panic崩溃后自定义处理方式
Golang GinWeb框架-快速入门/参数解析
Golang与亚马逊对象存储服务AmazonS3快速入门
Golang+Vue实现Websocket全双工通信入门
GolangWeb编程之控制器方法HandlerFunc与中间件Middleware
Golang连接MySQL执行查询并解析-告别结构体
Golang的一种发布订阅模式实现
Golang 并发数据冲突检测器(Data Race Detector)与并发安全
Golang"驱动"MongoDB-快速入门("快码加鞭")
点击 "阅读原文"获得更好阅读体验哦!点击[在看], 推荐给其他小伙伴哦!
*请认真填写需求信息,我们会在24小时内与您取得联系。