HTTP/2 Server Push

Requires go1.8+

How to send web assets using HTTP/2 server push?

Step 1: Generate a self-signed X.509 TLS certificate

Step 2: Register a route to serve web assets

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

Step 3: 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. })

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

Step 4: Configure TLS server using cert.pem and key.pem

  1. e.StartTLS(":1323", "cert.pem", "key.pem")

Step 5: 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

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>HTTP/2 Server Push</title>
  8. <link rel="stylesheet" href="/app.css">
  9. <script src="/app.js"></script>
  10. </head>
  11. <body>
  12. <img class="echo" src="/echo.png">
  13. <h2>The following static files are served via HTTP/2 server push</h2>
  14. <ul>
  15. <li><code>/app.css</code></li>
  16. <li><code>/app.js</code></li>
  17. <li><code>/echo.png</code></li>
  18. </ul>
  19. </body>
  20. </html>

server.go

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/labstack/echo"
  5. )
  6. func main() {
  7. e := echo.New()
  8. e.Static("/", "static")
  9. e.GET("/", func(c echo.Context) (err error) {
  10. pusher, ok := c.Response().Writer.(http.Pusher)
  11. if ok {
  12. if err = pusher.Push("/app.css", nil); err != nil {
  13. return
  14. }
  15. if err = pusher.Push("/app.js", nil); err != nil {
  16. return
  17. }
  18. if err = pusher.Push("/echo.png", nil); err != nil {
  19. return
  20. }
  21. }
  22. return c.File("index.html")
  23. })
  24. e.Logger.Fatal(e.StartTLS(":1323", "cert.pem", "key.pem"))
  25. }

Maintainers