HTTP2 server push

Full example code can be found at _examples/response-writer/http2push.

Server push lets the server preemptively “push” website assets to the client without the user having explicitly asked for them. When used with care, we can send what we know the user is going to need for the page they’re requesting.

  1. package main
  2. import (
  3. "net/http"
  4. "github.com/kataras/iris/v12"
  5. )
  6. func main() {
  7. app := iris.New()
  8. app.Get("/", pushHandler)
  9. app.Get("/main.js", simpleAssetHandler)
  10. app.Run(iris.TLS("127.0.0.1:443", "mycert.crt", "mykey.key"))
  11. // $ openssl req -new -newkey rsa:4096 -x509 -sha256 \
  12. // -days 365 -nodes -out mycert.crt -keyout mykey.key
  13. }
  14. func pushHandler(ctx iris.Context) {
  15. // The target must either be an absolute path (like "/path") or an absolute
  16. // URL that contains a valid host and the same scheme as the parent request.
  17. // If the target is a path, it will inherit the scheme and host of the
  18. // parent request.
  19. target := "/main.js"
  20. if pusher, ok := ctx.ResponseWriter().Naive().(http.Pusher); ok {
  21. err := pusher.Push(target, nil)
  22. if err != nil {
  23. if err == iris.ErrPushNotSupported {
  24. ctx.StopWithText(iris.StatusHTTPVersionNotSupported, "HTTP/2 push not supported.")
  25. } else {
  26. ctx.StopWithError(iris.StatusInternalServerError, err)
  27. }
  28. return
  29. }
  30. }
  31. ctx.HTML(`<html><body><script src="%s"></script></body></html>`, target)
  32. }
  33. func simpleAssetHandler(ctx iris.Context) {
  34. ctx.ServeFile("./public/main.js")
  35. }