我的Web服务器在Golang中编码并支持HTTPS.我希望利用Web服务器中的HTTP/2服务器推送功能.以下链接说明了如何将HTTP Server转换为支持HTTP/2: -
https://www.ianlewis.org/en/http2-and-go
但是,目前尚不清楚如何在Golang中实现服务器推送通知.
- 我应该如何添加服务器推送功能?
- 如何控制或管理要推送的文档和文件?
Go 1.7及更早版本不支持标准库中的HTTP/2服务器推送.即将发布的1.8版本中将添加对服务器推送的支持(请参阅发行说明,预计发布日期为2月).
使用Go 1.8,您可以使用新的http.Pusher接口,该接口由net/http的默认ResponseWriter实现.如果不支持服务器推送(HTTP/1)或不允许服务器推送(客户端已禁用服务器推送),则Pushers Push方法返回ErrNotSupported.
例:
package main
import (
"io"
"log"
"net/http"
)
func main() {
http.HandleFunc("/pushed", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "hello server push")
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if pusher, ok := w.(http.Pusher); ok {
if err := pusher.Push("/pushed", nil); err != nil {
log.Println("push failed")
}
}
io.WriteString(w, "hello world")
})
http.ListenAndServeTLS(":443", "server.crt", "server.key", nil)
}
Run Code Online (Sandbox Code Playgroud)
如果你想使用Go 1.7或更早版本的服务器推送,可以使用golang.org/x/net/http2并直接写入帧.