Search code examples
goserverhttp2

How to Make My Web Server written in Golang to support HTTP/2 Server Push?


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 ?


Solution

  • 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.