Skip to content

Instantly share code, notes, and snippets.

@nbari
Created February 18, 2017 11:21
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nbari/e19f195c233c92061e27f5beaaae45a3 to your computer and use it in GitHub Desktop.
HTTP/2 Push example
// HTTP/2 Push example using violetear
//
// Create certificate with:
// https://golang.org/src/crypto/tls/generate_cert.go
// go run generate_cert.go -host localhost,127.0.0.1 (will create cer.pem and key.pem)
//
// To test
// go run main.go and open browser using https://localhost:8000
package main
import (
"fmt"
"log"
"net/http"
"github.com/nbari/violetear"
)
const mainJS = `console.log("hello world");`
const indexHTML = `<html>
<head>
<title>Hello</title>
<script src="/main.js"></script>
</head>
<body>
</body>
</html>
`
func rootJS(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, mainJS)
}
func root(w http.ResponseWriter, r *http.Request) {
pusher, ok := w.(http.Pusher)
if ok {
if err := pusher.Push("/main.js", nil); err != nil {
log.Printf("Failed to push: %v", err)
}
}
fmt.Fprintf(w, indexHTML)
}
func main() {
router := violetear.New()
router.LogRequests = true
router.HandleFunc("/", root)
router.HandleFunc("main.js", rootJS)
log.Fatal(http.ListenAndServeTLS(":8000", "cert.pem", "key.pem", router))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment