-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathmain.go
47 lines (39 loc) · 1.39 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 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.
package main
import (
"fmt"
"net/http"
"github.com/kataras/muxie"
)
func main() {
mux := muxie.NewMux()
mux.HandleFunc("/", pushHandler)
mux.HandleFunc("/main.js", simpleAssetHandler)
http.ListenAndServeTLS(":443", "mycert.crt", "mykey.key", mux)
}
func pushHandler(w http.ResponseWriter, r *http.Request) {
// 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.
target := "/main.js"
if pusher, ok := w.(*muxie.Writer).ResponseWriter.(http.Pusher); ok {
err := pusher.Push(target, nil)
if err != nil {
if err == http.ErrNotSupported {
http.Error(w, "HTTP/2 push not supported", http.StatusHTTPVersionNotSupported)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, `<html><body><script src="%s"></script></body></html>`, target)
}
func simpleAssetHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./public/main.js")
}