跟着刘旭老师学go web做的笔记
【Go Web 编程快速入门【Golang/Go语言】(完结)】 https://www.bilibili.com/video/BV1Xv411k7Xn/?p=27&share_source=copy_web&vd_source=03c1dc52eeb3747825ecad0412c18ab1
https
【HTTP/1.1,HTTP/2和HTTP/3的区别】 https://www.bilibili.com/video/BV1vv4y1U77y/?share_source=copy_web&vd_source=03c1dc52eeb3747825ecad0412c18ab1
http 明文传输 中间人也能看见
https TLS传输层安全 加密数据,只有客户端和服务器知道它们在说啥
http Listener
http.ListenAndServe 函数
http.ListenAndServeTLS 函数
在Terminal里输入
go run E:\GO\src\crypto\tls\generate_cert.go -h
go run E:\GO\src\crypto\tls\generate_cert.go -host localhost
//就是你自己的储存目录下面的\src\crypto\tls\generate_cert.go
//设置加密证书
//出现 cert.pem 和key.pem文件
http.HandleFunc("/",func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
})
http.ListenAndServeTLS(":8080","cert.pem","key.pem",nil)
//现在是https://localhost:8080/了
HTTP/2
客户端与服务器沟通
HTTP/1.1 请求和响应
HTTP/2 Stream (每个数据类型都可以单独优化)
- 请求多路复用
- Header 压缩
- 默认安全
-
- HTTP ,但很多决定不支持 HTTP
-
- HTTPS
- Server Push
Server Push
http.HandleFunc("/home",func(w http.ResponseWriter, r *http.Request) {
if pusher,ok := w.(http.Pusher);ok{
pusher.Push("./css/app.css",&http.PushOptions{
Header: http.Header{"Content-Type": []string{"text/css"}},
})
}
t,_ := template.ParseFiles("home.html")
t.ExecuteTemplate(w,"home.html",nil)
})
http.ListenAndServeTLS(":8080","cert.pem","key.pem",nil)
测试
还没写完,等着过几天往上加代码
测试 Model 层
-
user_test.go
测试代码所在文件的名称以 _test 结尾
对于生产编译,不会包含以 _test 结尾的文件
对于测试编译,会包含以 _test 结尾的文件 -
func TestUpdatesModifiedTime(t *testing.T) { … }
测试函数名应以 Test 开头(需要导出)
函数名需要表达出被验证的特性
测试函数的参数类型是 *testing.T,它会提供测试相关的一些工具
测试 Controller 层
- 为了尽量保证单元测试的隔离性,测试不要使用例如数据库、外部API、文件系统等外部资源。
- 模拟请求和响应
- 需要使用 net/http/httptest 提供的功能
NewRequest 函数
- func NewRequest(method, url string, body io.Reader) (*Request, error)
-
- method:HTTP Method
-
- url:请求的 URL
-
- body:请求的 Body
-
- 返回的 *Request 可以传递给 handler 函数
ResponseRecorder
type ResponseRecorder {
Code int // 状态码 200、500…
HeaderMap http.Header // 响应的 header
Body *bytes.Buffer // 响应的 body
Flushed bool // 缓存是否被 flush 了
}
用来捕获从 handler 返回的响应,只是做记录
可以用于测试断言