go http2 server push 及client push handle 示例

1、項目初始化

在GOPATH之外,創建一個新目錄,並使用go mod init 初始化go.mod文件

sudo mkdir -p /opt/workspace/gomod/http2demo
cd /opt/workspace/gomod/http2demo
sudo go mod init github.com/custhk/http2demo

其它go mod命令

命令 說明
init initialize new module in current directory(在當前目錄初始化mod)
download download modules to local cache(下載依賴包)
edit edit go.mod from tools or scripts(編輯go.mod)
tidy add missing and remove unused modules(拉取缺少的模塊,移除不用的模塊)
graph print module requirement graph (打印模塊依賴圖)
vendor make vendored copy of dependencies(將依賴複製到vendor下)
verify verify dependencies have expected content (驗證依賴是否正確)
why explain why packages or modules are needed(解釋爲什麼需要依賴)

2、http2依賴替換(替換後client支持push handle)

go.mod 提供了module, require、replace和exclude 四個命令來配置依賴,其中replace命令用於依賴替換

命令 說明
module 語句指定包的名字(路徑)
require 語句指定的依賴項模塊
replace 語句可以替換依賴項模塊
exclude 語句可以忽略依賴項模塊

替換net/http2爲支持client push handle的net/http包

sudo gedit /opt/workspace/gomod/http2demo/go.mod

## 添加
require golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e

replace golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e => github.com/custhk/net v0.0.0-20200326042854-adbd26198b9f

3、項目結構

在這裏插入圖片描述

client:客戶端相關內容
pem:證書相關內容
resdata:資源
resource:資源數據結構
server:服務器相關內容

4、生成證書

sudo mkdir -p /opt/workspace/gomod/http2demo/pem
cd /opt/workspace/gomod/http2demo/pem
sudo gedit generate_cert.go

## 拷貝
## https://github.com/golang/go/blob/master/src/crypto/tls/generate_cert.go
## 內容到generate_cert.go內

## 下載依賴
cd /opt/workspace/gomod/http2demo/
export GOPROXY=https://goproxy.io
go mod download

## 這裏生成了pem格式的證書和祕鑰
cd /opt/workspace/gomod/http2demo/pem
sudo go run ./generate_cert.go --host localhost

5、編寫客戶端及服務端代碼

github倉庫地址:
https://github.com/custhk/http2demo

6、測試(需要先用瀏覽器訪問一遍,並選擇信賴)

瀏覽器直接訪問(no push)
在這裏插入圖片描述
在這裏插入圖片描述

用客戶端訪問(指定push)服務器端採用push

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章