July 2019
Intermediate to advanced
458 pages
12h 12m
English
We have already discussed that Golang supports the HTTP/2 server side push functionality since version 1.8. Let's see how to use it in an application. Its usage is pretty simple; if the request can be casted to the http.Pusher interface, it can be used to push additional requests in the main interface. In this example, we use it to sideload a SVG image, together with the page:
func main() { const imgPath = "/image.svg" http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { pusher, ok := w.(http.Pusher) if ok { fmt.Println("Push /image") pusher.Push(imgPath, nil) } w.Header().Add("Content-Type", "text/html") fmt.Fprintf(w, `<html><body><img src="%s"/>`+ `</body></html>`, imgPath) }) http.HandleFunc(imgPath, func(w ...Read now
Unlock full access