douwuying4709 2017-01-05 16:48
浏览 323
已采纳

如何使我的Web服务器用Golang编写以支持HTTP / 2服务器推送?

My Web Server is Coded in Golang and supports HTTPS. I wish to leverage HTTP/2 Server Push features in the Web Server. The following Link explains how to convert HTTP Server to Support HTTP/2 :- https://www.ianlewis.org/en/http2-and-go
However, it is not clear how to implement the Server Push notifications in Golang.
- How should I add the Server Push functionality ?
- How do I control, or manage, the documents and files to be Pushed ?

  • 写回答

2条回答 默认 最新

  • duanbi1983 2017-01-05 17:36
    关注

    Go 1.7 and older do not support HTTP/2 server push in the standard library. Support for server push will be added in the upcoming 1.8 release (see the release notes, expected release is February).

    With Go 1.8 you can use the new http.Pusher interface, which is implemented by net/http's default ResponseWriter. Pushers Push method returns ErrNotSupported, if server push is not supported (HTTP/1) or not allowed (the client has disabled server push).

    Example:

    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)
    }
    

    If you want to use server push with Go 1.7 or older use can use the golang.org/x/net/http2 and write the frames directly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题