Skip to content

Instantly share code, notes, and snippets.

@crhntr
Created March 19, 2017 21:09
Show Gist options
  • Save crhntr/cc02fead451b7d31f67fda2bd8ff6741 to your computer and use it in GitHub Desktop.
Save crhntr/cc02fead451b7d31f67fda2bd8ff6741 to your computer and use it in GitHub Desktop.
An HTTP2 push example program for go
// golang http2 example
// run these before: openssl genrsa -out server.key 2048
// openssl ecparam -genkey -name secp384r1 -out server.key
// openssl req -new -x509 -sha256 -key server.key -out server.crt -days 3650
package main
import (
"log"
"net/http"
"time"
)
func PushAlertHandler(w http.ResponseWriter, r *http.Request) {
log.Println("/alert")
time.Sleep(3 * time.Second)
w.Header().Set("Content-Type", "application/javascript")
w.Write([]byte(`alert("you got me");`))
}
func HelloHandler2(w http.ResponseWriter, r *http.Request) {
log.Println("/2")
if pw, ok := w.(http.Pusher); ok {
log.Println("attempting push")
if err := pw.Push("/alert", nil); err != nil {
log.Println("push failed")
}
}
time.Sleep(3 * time.Second)
w.Header().Set("Content-Type", "text/html")
w.Write([]byte("<!DOCTYPE html><html><head><script src=\"/alert\"></script></head><body><p>This is an example server.</p></body></html>"))
}
func HelloHandler1(w http.ResponseWriter, r *http.Request) {
log.Println("/1")
time.Sleep(3 * time.Second)
w.Header().Set("Content-Type", "text/html")
w.Write([]byte("<!DOCTYPE html><html><head><script src=\"/alert\"></script></head><body><p>This is an example server.</p></body></html>"))
}
func IndexHandler(w http.ResponseWriter, r *http.Request) {
log.Println("/")
w.Header().Set("Content-Type", "text/html")
w.Write([]byte("<!DOCTYPE html><html><head></head><body><a href=\"/1\">1</a><br><a href=\"/2\">2</a></body></html>"))
}
func main() {
http.HandleFunc("/", IndexHandler)
http.HandleFunc("/2", HelloHandler2)
http.HandleFunc("/1", HelloHandler1)
http.HandleFunc("/alert", PushAlertHandler)
err := http.ListenAndServeTLS(":8443", "server.crt", "server.key", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment