HTTP/2 Push
Content-Type: *
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.
The target must either be an absolute path (like "/path") or an absolute URL that contains a valid host and the same scheme as the parent request. If the target is a path, it will inherit the scheme and host of the parent request.
1
Context.ResponseWriter().Push(target string, opts *http.PushOptions) error
Copied!
The Push method returns iris.ErrPushNotSupported if the client has disabled push or if push is not supported on the underlying connection.

Example

The Push feature works only on HTTP/2 servers.
Create the project structure, e.g.
1
│ main.go
2
└───public
3
│ main.js
Copied!
The main.js contains a simple alert function:
1
window.alert("javascript loaded");
Copied!
Execute the following command to generate sample server keys:
1
$ openssl req -new -newkey rsa:4096 -x509 -sha256 \
2
-days 365 -nodes -out mycert.crt -keyout mykey.key
Copied!
Create the main.go file and copy-paste the code below:
1
package main
2
3
import "github.com/kataras/iris/v12"
4
5
func main() {
6
app := iris.New()
7
app.Get("/", pushHandler)
8
app.Get("/main.js", simpleAssetHandler)
9
10
app.Run(iris.TLS("127.0.0.1:443", "mycert.crt", "mykey.key"))
11
}
12
13
func pushHandler(ctx iris.Context) {
14
target := "/main.js"
15
err := ctx.ResponseWriter().Push(target, nil)
16
if err != nil {
17
if err == iris.ErrPushNotSupported {
18
ctx.StopWithText(iris.StatusHTTPVersionNotSupported,
19
"HTTP/2 push not supported.")
20
} else {
21
ctx.StopWithError(iris.StatusInternalServerError, err)
22
}
23
return
24
}
25
26
ctx.HTML(`<html><body><script src="%s"></script></body></html>`, target)
27
}
28
29
func simpleAssetHandler(ctx iris.Context) {
30
ctx.ServeFile("./public/main.js")
31
}
Copied!
Run the server:
1
$ go run main.go
Copied!
Now, open your browser's developer tools and click the Network tab. Navigate to https://127.0.0.1/, the main.js Initiator should be Push / (index) as shown below:
Last modified 1yr ago
Export as PDF
Copy link
Contents
Example