Instantly share code, notes, and snippets.

Embed
What would you like to do?
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