HTTP/2 Server Push

HTTP/2 Server Push - 图1note

Requires go1.8+

Send web assets using HTTP/2 server push

Generate a self-signed X.509 TLS certificate

1) Register a route to serve web assets

  1. e.Static("/", "static")

2) Create a handler to serve index.html and push it’s dependencies

  1. e.GET("/", func(c echo.Context) (err error) {
  2. pusher, ok := c.Response().Writer.(http.Pusher)
  3. if ok {
  4. if err = pusher.Push("/app.css", nil); err != nil {
  5. return
  6. }
  7. if err = pusher.Push("/app.js", nil); err != nil {
  8. return
  9. }
  10. if err = pusher.Push("/echo.png", nil); err != nil {
  11. return
  12. }
  13. }
  14. return c.File("index.html")
  15. })

HTTP/2 Server Push - 图2info

If http.Pusher is supported, web assets are pushed; otherwise, client makes separate requests to get them.

3) Start TLS server using cert.pem and key.pem

  1. if err := e.StartTLS(":1323", "cert.pem", "key.pem"); err != http.ErrServerClosed {
  2. log.Fatal(err)
  3. }

or use customized HTTP server with your own TLSConfig

  1. s := http.Server{
  2. Addr: ":8443",
  3. Handler: e, // set Echo as handler
  4. TLSConfig: &tls.Config{
  5. //Certificates: nil, // <-- s.ListenAndServeTLS will populate this field
  6. },
  7. //ReadTimeout: 30 * time.Second, // use custom timeouts
  8. }
  9. if err := s.ListenAndServeTLS("cert.pem", "key.pem"); err != http.ErrServerClosed {
  10. log.Fatal(err)
  11. }

4) Start the server and browse to https://localhost:1323

  1. Protocol: HTTP/2.0
  2. Host: localhost:1323
  3. Remote Address: [::1]:60288
  4. Method: GET
  5. Path: /

Source Code

cookbook/http2-server-push/index.html

  1. loading...

cookbook/http2-server-push/server.go

  1. loading...