h2demo.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // Copyright 2014 The Go Authors.
  2. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS
  3. // Licensed under the same terms as Go itself:
  4. // https://code.google.com/p/go/source/browse/LICENSE
  5. // +build h2demo
  6. package main
  7. import (
  8. "bytes"
  9. "crypto/tls"
  10. "flag"
  11. "fmt"
  12. "hash/crc32"
  13. "image"
  14. "image/jpeg"
  15. "io"
  16. "io/ioutil"
  17. "log"
  18. "net"
  19. "net/http"
  20. "os/exec"
  21. "path"
  22. "regexp"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "sync"
  27. "time"
  28. "camlistore.org/pkg/googlestorage"
  29. "camlistore.org/pkg/singleflight"
  30. "golang.org/x/net/http2"
  31. )
  32. var (
  33. openFirefox = flag.Bool("openff", false, "Open Firefox")
  34. addr = flag.String("addr", "localhost:4430", "TLS address to listen on")
  35. httpAddr = flag.String("httpaddr", "", "If non-empty, address to listen for regular HTTP on")
  36. prod = flag.Bool("prod", false, "Whether to configure itself to be the production http2.golang.org server.")
  37. )
  38. func homeOldHTTP(w http.ResponseWriter, r *http.Request) {
  39. io.WriteString(w, `<html>
  40. <body>
  41. <h1>Go + HTTP/2</h1>
  42. <p>Welcome to <a href="https://golang.org/">the Go language</a>'s <a href="https://http2.github.io/">HTTP/2</a> demo & interop server.</p>
  43. <p>Unfortunately, you're <b>not</b> using HTTP/2 right now. To do so:</p>
  44. <ul>
  45. <li>Use Firefox Nightly or go to <b>about:config</b> and enable "network.http.spdy.enabled.http2draft"</li>
  46. <li>Use Google Chrome Canary and/or go to <b>chrome://flags/#enable-spdy4</b> to <i>Enable SPDY/4</i> (Chrome's name for HTTP/2)</li>
  47. </ul>
  48. <p>See code & instructions for connecting at <a href="https://github.com/golang/net/tree/master/http2">https://github.com/golang/net/tree/master/http2</a>.</p>
  49. </body></html>`)
  50. }
  51. func home(w http.ResponseWriter, r *http.Request) {
  52. if r.URL.Path != "/" {
  53. http.NotFound(w, r)
  54. return
  55. }
  56. io.WriteString(w, `<html>
  57. <body>
  58. <h1>Go + HTTP/2</h1>
  59. <p>Welcome to <a href="https://golang.org/">the Go language</a>'s <a
  60. href="https://http2.github.io/">HTTP/2</a> demo & interop server.</p>
  61. <p>Congratulations, <b>you're using HTTP/2 right now</b>.</p>
  62. <p>This server exists for others in the HTTP/2 community to test their HTTP/2 client implementations and point out flaws in our server.</p>
  63. <p> The code is currently at <a
  64. href="https://golang.org/x/net/http2">github.com/bradfitz/http2</a>
  65. but will move to the Go standard library at some point in the future
  66. (enabled by default, without users needing to change their code).</p>
  67. <p>Contact info: <i>bradfitz@golang.org</i>, or <a
  68. href="https://golang.org/x/net/http2/issues">file a bug</a>.</p>
  69. <h2>Handlers for testing</h2>
  70. <ul>
  71. <li>GET <a href="/reqinfo">/reqinfo</a> to dump the request + headers received</li>
  72. <li>GET <a href="/clockstream">/clockstream</a> streams the current time every second</li>
  73. <li>GET <a href="/gophertiles">/gophertiles</a> to see a page with a bunch of images</li>
  74. <li>GET <a href="/file/gopher.png">/file/gopher.png</a> for a small file (does If-Modified-Since, Content-Range, etc)</li>
  75. <li>GET <a href="/file/go.src.tar.gz">/file/go.src.tar.gz</a> for a larger file (~10 MB)</li>
  76. <li>GET <a href="/redirect">/redirect</a> to redirect back to / (this page)</li>
  77. <li>GET <a href="/goroutines">/goroutines</a> to see all active goroutines in this server</li>
  78. <li>PUT something to <a href="/crc32">/crc32</a> to get a count of number of bytes and its CRC-32</li>
  79. </ul>
  80. </body></html>`)
  81. }
  82. func reqInfoHandler(w http.ResponseWriter, r *http.Request) {
  83. w.Header().Set("Content-Type", "text/plain")
  84. fmt.Fprintf(w, "Method: %s\n", r.Method)
  85. fmt.Fprintf(w, "Protocol: %s\n", r.Proto)
  86. fmt.Fprintf(w, "Host: %s\n", r.Host)
  87. fmt.Fprintf(w, "RemoteAddr: %s\n", r.RemoteAddr)
  88. fmt.Fprintf(w, "RequestURI: %q\n", r.RequestURI)
  89. fmt.Fprintf(w, "URL: %#v\n", r.URL)
  90. fmt.Fprintf(w, "Body.ContentLength: %d (-1 means unknown)\n", r.ContentLength)
  91. fmt.Fprintf(w, "Close: %v (relevant for HTTP/1 only)\n", r.Close)
  92. fmt.Fprintf(w, "TLS: %#v\n", r.TLS)
  93. fmt.Fprintf(w, "\nHeaders:\n")
  94. r.Header.Write(w)
  95. }
  96. func crcHandler(w http.ResponseWriter, r *http.Request) {
  97. if r.Method != "PUT" {
  98. http.Error(w, "PUT required.", 400)
  99. return
  100. }
  101. crc := crc32.NewIEEE()
  102. n, err := io.Copy(crc, r.Body)
  103. if err == nil {
  104. w.Header().Set("Content-Type", "text/plain")
  105. fmt.Fprintf(w, "bytes=%d, CRC32=%x", n, crc.Sum(nil))
  106. }
  107. }
  108. var (
  109. fsGrp singleflight.Group
  110. fsMu sync.Mutex // guards fsCache
  111. fsCache = map[string]http.Handler{}
  112. )
  113. // fileServer returns a file-serving handler that proxies URL.
  114. // It lazily fetches URL on the first access and caches its contents forever.
  115. func fileServer(url string) http.Handler {
  116. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  117. hi, err := fsGrp.Do(url, func() (interface{}, error) {
  118. fsMu.Lock()
  119. if h, ok := fsCache[url]; ok {
  120. fsMu.Unlock()
  121. return h, nil
  122. }
  123. fsMu.Unlock()
  124. res, err := http.Get(url)
  125. if err != nil {
  126. return nil, err
  127. }
  128. defer res.Body.Close()
  129. slurp, err := ioutil.ReadAll(res.Body)
  130. if err != nil {
  131. return nil, err
  132. }
  133. modTime := time.Now()
  134. var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  135. http.ServeContent(w, r, path.Base(url), modTime, bytes.NewReader(slurp))
  136. })
  137. fsMu.Lock()
  138. fsCache[url] = h
  139. fsMu.Unlock()
  140. return h, nil
  141. })
  142. if err != nil {
  143. http.Error(w, err.Error(), 500)
  144. return
  145. }
  146. hi.(http.Handler).ServeHTTP(w, r)
  147. })
  148. }
  149. func clockStreamHandler(w http.ResponseWriter, r *http.Request) {
  150. clientGone := w.(http.CloseNotifier).CloseNotify()
  151. w.Header().Set("Content-Type", "text/plain")
  152. ticker := time.NewTicker(1 * time.Second)
  153. defer ticker.Stop()
  154. fmt.Fprintf(w, "# ~1KB of junk to force browsers to start rendering immediately: \n")
  155. io.WriteString(w, strings.Repeat("# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n", 13))
  156. for {
  157. fmt.Fprintf(w, "%v\n", time.Now())
  158. w.(http.Flusher).Flush()
  159. select {
  160. case <-ticker.C:
  161. case <-clientGone:
  162. log.Printf("Client %v disconnected from the clock", r.RemoteAddr)
  163. return
  164. }
  165. }
  166. }
  167. func registerHandlers() {
  168. tiles := newGopherTilesHandler()
  169. mux2 := http.NewServeMux()
  170. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  171. if r.TLS == nil {
  172. if r.URL.Path == "/gophertiles" {
  173. tiles.ServeHTTP(w, r)
  174. return
  175. }
  176. http.Redirect(w, r, "https://http2.golang.org/", http.StatusFound)
  177. return
  178. }
  179. if r.ProtoMajor == 1 {
  180. if r.URL.Path == "/reqinfo" {
  181. reqInfoHandler(w, r)
  182. return
  183. }
  184. homeOldHTTP(w, r)
  185. return
  186. }
  187. mux2.ServeHTTP(w, r)
  188. })
  189. mux2.HandleFunc("/", home)
  190. mux2.Handle("/file/gopher.png", fileServer("https://golang.org/doc/gopher/frontpage.png"))
  191. mux2.Handle("/file/go.src.tar.gz", fileServer("https://storage.googleapis.com/golang/go1.4.1.src.tar.gz"))
  192. mux2.HandleFunc("/reqinfo", reqInfoHandler)
  193. mux2.HandleFunc("/crc32", crcHandler)
  194. mux2.HandleFunc("/clockstream", clockStreamHandler)
  195. mux2.Handle("/gophertiles", tiles)
  196. mux2.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
  197. http.Redirect(w, r, "/", http.StatusFound)
  198. })
  199. stripHomedir := regexp.MustCompile(`/(Users|home)/\w+`)
  200. mux2.HandleFunc("/goroutines", func(w http.ResponseWriter, r *http.Request) {
  201. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  202. buf := make([]byte, 2<<20)
  203. w.Write(stripHomedir.ReplaceAll(buf[:runtime.Stack(buf, true)], nil))
  204. })
  205. }
  206. func newGopherTilesHandler() http.Handler {
  207. const gopherURL = "https://blog.golang.org/go-programming-language-turns-two_gophers.jpg"
  208. res, err := http.Get(gopherURL)
  209. if err != nil {
  210. log.Fatal(err)
  211. }
  212. if res.StatusCode != 200 {
  213. log.Fatalf("Error fetching %s: %v", gopherURL, res.Status)
  214. }
  215. slurp, err := ioutil.ReadAll(res.Body)
  216. res.Body.Close()
  217. if err != nil {
  218. log.Fatal(err)
  219. }
  220. im, err := jpeg.Decode(bytes.NewReader(slurp))
  221. if err != nil {
  222. if len(slurp) > 1024 {
  223. slurp = slurp[:1024]
  224. }
  225. log.Fatalf("Failed to decode gopher image: %v (got %q)", err, slurp)
  226. }
  227. type subImager interface {
  228. SubImage(image.Rectangle) image.Image
  229. }
  230. const tileSize = 32
  231. xt := im.Bounds().Max.X / tileSize
  232. yt := im.Bounds().Max.Y / tileSize
  233. var tile [][][]byte // y -> x -> jpeg bytes
  234. for yi := 0; yi < yt; yi++ {
  235. var row [][]byte
  236. for xi := 0; xi < xt; xi++ {
  237. si := im.(subImager).SubImage(image.Rectangle{
  238. Min: image.Point{xi * tileSize, yi * tileSize},
  239. Max: image.Point{(xi + 1) * tileSize, (yi + 1) * tileSize},
  240. })
  241. buf := new(bytes.Buffer)
  242. if err := jpeg.Encode(buf, si, &jpeg.Options{Quality: 90}); err != nil {
  243. log.Fatal(err)
  244. }
  245. row = append(row, buf.Bytes())
  246. }
  247. tile = append(tile, row)
  248. }
  249. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  250. ms, _ := strconv.Atoi(r.FormValue("latency"))
  251. const nanosPerMilli = 1e6
  252. if r.FormValue("x") != "" {
  253. x, _ := strconv.Atoi(r.FormValue("x"))
  254. y, _ := strconv.Atoi(r.FormValue("y"))
  255. if ms <= 1000 {
  256. time.Sleep(time.Duration(ms) * nanosPerMilli)
  257. }
  258. if x >= 0 && x < xt && y >= 0 && y < yt {
  259. http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(tile[y][x]))
  260. return
  261. }
  262. }
  263. io.WriteString(w, "<html><body>")
  264. fmt.Fprintf(w, "A grid of %d tiled images is below. Compare:<p>", xt*yt)
  265. for _, ms := range []int{0, 30, 200, 1000} {
  266. d := time.Duration(ms) * nanosPerMilli
  267. fmt.Fprintf(w, "[<a href='https://%s/gophertiles?latency=%d'>HTTP/2, %v latency</a>] [<a href='http://%s/gophertiles?latency=%d'>HTTP/1, %v latency</a>]<br>\n",
  268. httpsHost(), ms, d,
  269. httpHost(), ms, d,
  270. )
  271. }
  272. io.WriteString(w, "<p>\n")
  273. cacheBust := time.Now().UnixNano()
  274. for y := 0; y < yt; y++ {
  275. for x := 0; x < xt; x++ {
  276. fmt.Fprintf(w, "<img width=%d height=%d src='/gophertiles?x=%d&y=%d&cachebust=%d&latency=%d'>",
  277. tileSize, tileSize, x, y, cacheBust, ms)
  278. }
  279. io.WriteString(w, "<br/>\n")
  280. }
  281. io.WriteString(w, "<hr><a href='/'>&lt;&lt Back to Go HTTP/2 demo server</a></body></html>")
  282. })
  283. }
  284. func httpsHost() string {
  285. if *prod {
  286. return "http2.golang.org"
  287. }
  288. if v := *addr; strings.HasPrefix(v, ":") {
  289. return "localhost" + v
  290. } else {
  291. return v
  292. }
  293. }
  294. func httpHost() string {
  295. if *prod {
  296. return "http2.golang.org"
  297. }
  298. if v := *httpAddr; strings.HasPrefix(v, ":") {
  299. return "localhost" + v
  300. } else {
  301. return v
  302. }
  303. }
  304. func serveProdTLS() error {
  305. c, err := googlestorage.NewServiceClient()
  306. if err != nil {
  307. return err
  308. }
  309. slurp := func(key string) ([]byte, error) {
  310. const bucket = "http2-demo-server-tls"
  311. rc, _, err := c.GetObject(&googlestorage.Object{
  312. Bucket: bucket,
  313. Key: key,
  314. })
  315. if err != nil {
  316. return nil, fmt.Errorf("Error fetching GCS object %q in bucket %q: %v", key, bucket, err)
  317. }
  318. defer rc.Close()
  319. return ioutil.ReadAll(rc)
  320. }
  321. certPem, err := slurp("http2.golang.org.chained.pem")
  322. if err != nil {
  323. return err
  324. }
  325. keyPem, err := slurp("http2.golang.org.key")
  326. if err != nil {
  327. return err
  328. }
  329. cert, err := tls.X509KeyPair(certPem, keyPem)
  330. if err != nil {
  331. return err
  332. }
  333. srv := &http.Server{
  334. TLSConfig: &tls.Config{
  335. Certificates: []tls.Certificate{cert},
  336. },
  337. }
  338. http2.ConfigureServer(srv, &http2.Server{})
  339. ln, err := net.Listen("tcp", ":443")
  340. if err != nil {
  341. return err
  342. }
  343. return srv.Serve(tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, srv.TLSConfig))
  344. }
  345. type tcpKeepAliveListener struct {
  346. *net.TCPListener
  347. }
  348. func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
  349. tc, err := ln.AcceptTCP()
  350. if err != nil {
  351. return
  352. }
  353. tc.SetKeepAlive(true)
  354. tc.SetKeepAlivePeriod(3 * time.Minute)
  355. return tc, nil
  356. }
  357. func serveProd() error {
  358. errc := make(chan error, 2)
  359. go func() { errc <- http.ListenAndServe(":80", nil) }()
  360. go func() { errc <- serveProdTLS() }()
  361. return <-errc
  362. }
  363. func main() {
  364. var srv http.Server
  365. flag.BoolVar(&http2.VerboseLogs, "verbose", false, "Verbose HTTP/2 debugging.")
  366. flag.Parse()
  367. srv.Addr = *addr
  368. registerHandlers()
  369. if *prod {
  370. *httpAddr = "http2.golang.org"
  371. log.Fatal(serveProd())
  372. }
  373. url := "https://" + *addr + "/"
  374. log.Printf("Listening on " + url)
  375. http2.ConfigureServer(&srv, &http2.Server{})
  376. if *httpAddr != "" {
  377. go func() { log.Fatal(http.ListenAndServe(*httpAddr, nil)) }()
  378. }
  379. go func() {
  380. log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
  381. }()
  382. if *openFirefox && runtime.GOOS == "darwin" {
  383. time.Sleep(250 * time.Millisecond)
  384. exec.Command("open", "-b", "org.mozilla.nightly", "https://localhost:4430/").Run()
  385. }
  386. select {}
  387. }