h2demo.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build h2demo
  5. package main
  6. import (
  7. "bytes"
  8. "context"
  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. "path"
  21. "regexp"
  22. "runtime"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "time"
  27. "cloud.google.com/go/storage"
  28. "go4.org/syncutil/singleflight"
  29. "golang.org/x/build/autocertcache"
  30. "golang.org/x/crypto/acme/autocert"
  31. "golang.org/x/net/http2"
  32. )
  33. var (
  34. prod = flag.Bool("prod", false, "Whether to configure itself to be the production http2.golang.org server.")
  35. httpsAddr = flag.String("https_addr", "localhost:4430", "TLS address to listen on ('host:port' or ':port'). Required.")
  36. httpAddr = flag.String("http_addr", "", "Plain HTTP address to listen on ('host:port', or ':port'). Empty means no HTTP.")
  37. hostHTTP = flag.String("http_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -http_addr.")
  38. hostHTTPS = flag.String("https_host", "", "Optional host or host:port to use for http:// links to this service. By default, this is implied from -https_addr.")
  39. )
  40. func homeOldHTTP(w http.ResponseWriter, r *http.Request) {
  41. io.WriteString(w, `<html>
  42. <body>
  43. <h1>Go + HTTP/2</h1>
  44. <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>
  45. <p>Unfortunately, you're <b>not</b> using HTTP/2 right now. To do so:</p>
  46. <ul>
  47. <li>Use Firefox Nightly or go to <b>about:config</b> and enable "network.http.spdy.enabled.http2draft"</li>
  48. <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>
  49. </ul>
  50. <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>
  51. </body></html>`)
  52. }
  53. func home(w http.ResponseWriter, r *http.Request) {
  54. if r.URL.Path != "/" {
  55. http.NotFound(w, r)
  56. return
  57. }
  58. io.WriteString(w, `<html>
  59. <body>
  60. <h1>Go + HTTP/2</h1>
  61. <p>Welcome to <a href="https://golang.org/">the Go language</a>'s <a
  62. href="https://http2.github.io/">HTTP/2</a> demo & interop server.</p>
  63. <p>Congratulations, <b>you're using HTTP/2 right now</b>.</p>
  64. <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>
  65. <p>
  66. The code is at <a href="https://golang.org/x/net/http2">golang.org/x/net/http2</a> and
  67. is used transparently by the Go standard library from Go 1.6 and later.
  68. </p>
  69. <p>Contact info: <i>bradfitz@golang.org</i>, or <a
  70. href="https://golang.org/s/http2bug">file a bug</a>.</p>
  71. <h2>Handlers for testing</h2>
  72. <ul>
  73. <li>GET <a href="/reqinfo">/reqinfo</a> to dump the request + headers received</li>
  74. <li>GET <a href="/clockstream">/clockstream</a> streams the current time every second</li>
  75. <li>GET <a href="/gophertiles">/gophertiles</a> to see a page with a bunch of images</li>
  76. <li>GET <a href="/serverpush">/serverpush</a> to see a page with server push</li>
  77. <li>GET <a href="/file/gopher.png">/file/gopher.png</a> for a small file (does If-Modified-Since, Content-Range, etc)</li>
  78. <li>GET <a href="/file/go.src.tar.gz">/file/go.src.tar.gz</a> for a larger file (~10 MB)</li>
  79. <li>GET <a href="/redirect">/redirect</a> to redirect back to / (this page)</li>
  80. <li>GET <a href="/goroutines">/goroutines</a> to see all active goroutines in this server</li>
  81. <li>PUT something to <a href="/crc32">/crc32</a> to get a count of number of bytes and its CRC-32</li>
  82. <li>PUT something to <a href="/ECHO">/ECHO</a> and it will be streamed back to you capitalized</li>
  83. </ul>
  84. </body></html>`)
  85. }
  86. func reqInfoHandler(w http.ResponseWriter, r *http.Request) {
  87. w.Header().Set("Content-Type", "text/plain")
  88. fmt.Fprintf(w, "Method: %s\n", r.Method)
  89. fmt.Fprintf(w, "Protocol: %s\n", r.Proto)
  90. fmt.Fprintf(w, "Host: %s\n", r.Host)
  91. fmt.Fprintf(w, "RemoteAddr: %s\n", r.RemoteAddr)
  92. fmt.Fprintf(w, "RequestURI: %q\n", r.RequestURI)
  93. fmt.Fprintf(w, "URL: %#v\n", r.URL)
  94. fmt.Fprintf(w, "Body.ContentLength: %d (-1 means unknown)\n", r.ContentLength)
  95. fmt.Fprintf(w, "Close: %v (relevant for HTTP/1 only)\n", r.Close)
  96. fmt.Fprintf(w, "TLS: %#v\n", r.TLS)
  97. fmt.Fprintf(w, "\nHeaders:\n")
  98. r.Header.Write(w)
  99. }
  100. func crcHandler(w http.ResponseWriter, r *http.Request) {
  101. if r.Method != "PUT" {
  102. http.Error(w, "PUT required.", 400)
  103. return
  104. }
  105. crc := crc32.NewIEEE()
  106. n, err := io.Copy(crc, r.Body)
  107. if err == nil {
  108. w.Header().Set("Content-Type", "text/plain")
  109. fmt.Fprintf(w, "bytes=%d, CRC32=%x", n, crc.Sum(nil))
  110. }
  111. }
  112. type capitalizeReader struct {
  113. r io.Reader
  114. }
  115. func (cr capitalizeReader) Read(p []byte) (n int, err error) {
  116. n, err = cr.r.Read(p)
  117. for i, b := range p[:n] {
  118. if b >= 'a' && b <= 'z' {
  119. p[i] = b - ('a' - 'A')
  120. }
  121. }
  122. return
  123. }
  124. type flushWriter struct {
  125. w io.Writer
  126. }
  127. func (fw flushWriter) Write(p []byte) (n int, err error) {
  128. n, err = fw.w.Write(p)
  129. if f, ok := fw.w.(http.Flusher); ok {
  130. f.Flush()
  131. }
  132. return
  133. }
  134. func echoCapitalHandler(w http.ResponseWriter, r *http.Request) {
  135. if r.Method != "PUT" {
  136. http.Error(w, "PUT required.", 400)
  137. return
  138. }
  139. if f, ok := w.(http.Flusher); ok {
  140. f.Flush()
  141. }
  142. io.Copy(flushWriter{w}, capitalizeReader{r.Body})
  143. }
  144. var (
  145. fsGrp singleflight.Group
  146. fsMu sync.Mutex // guards fsCache
  147. fsCache = map[string]http.Handler{}
  148. )
  149. // fileServer returns a file-serving handler that proxies URL.
  150. // It lazily fetches URL on the first access and caches its contents forever.
  151. func fileServer(url string, latency time.Duration) http.Handler {
  152. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  153. if latency > 0 {
  154. time.Sleep(latency)
  155. }
  156. hi, err := fsGrp.Do(url, func() (interface{}, error) {
  157. fsMu.Lock()
  158. if h, ok := fsCache[url]; ok {
  159. fsMu.Unlock()
  160. return h, nil
  161. }
  162. fsMu.Unlock()
  163. res, err := http.Get(url)
  164. if err != nil {
  165. return nil, err
  166. }
  167. defer res.Body.Close()
  168. slurp, err := ioutil.ReadAll(res.Body)
  169. if err != nil {
  170. return nil, err
  171. }
  172. modTime := time.Now()
  173. var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  174. http.ServeContent(w, r, path.Base(url), modTime, bytes.NewReader(slurp))
  175. })
  176. fsMu.Lock()
  177. fsCache[url] = h
  178. fsMu.Unlock()
  179. return h, nil
  180. })
  181. if err != nil {
  182. http.Error(w, err.Error(), 500)
  183. return
  184. }
  185. hi.(http.Handler).ServeHTTP(w, r)
  186. })
  187. }
  188. func clockStreamHandler(w http.ResponseWriter, r *http.Request) {
  189. clientGone := w.(http.CloseNotifier).CloseNotify()
  190. w.Header().Set("Content-Type", "text/plain")
  191. ticker := time.NewTicker(1 * time.Second)
  192. defer ticker.Stop()
  193. fmt.Fprintf(w, "# ~1KB of junk to force browsers to start rendering immediately: \n")
  194. io.WriteString(w, strings.Repeat("# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n", 13))
  195. for {
  196. fmt.Fprintf(w, "%v\n", time.Now())
  197. w.(http.Flusher).Flush()
  198. select {
  199. case <-ticker.C:
  200. case <-clientGone:
  201. log.Printf("Client %v disconnected from the clock", r.RemoteAddr)
  202. return
  203. }
  204. }
  205. }
  206. func registerHandlers() {
  207. tiles := newGopherTilesHandler()
  208. push := newPushHandler()
  209. mux2 := http.NewServeMux()
  210. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  211. switch {
  212. case r.URL.Path == "/gophertiles":
  213. tiles.ServeHTTP(w, r) // allow HTTP/2 + HTTP/1.x
  214. return
  215. case strings.HasPrefix(r.URL.Path, "/serverpush"):
  216. push.ServeHTTP(w, r) // allow HTTP/2 + HTTP/1.x
  217. return
  218. case r.TLS == nil: // do not allow HTTP/1.x for anything else
  219. http.Redirect(w, r, "https://"+httpsHost()+"/", http.StatusFound)
  220. return
  221. }
  222. if r.ProtoMajor == 1 {
  223. if r.URL.Path == "/reqinfo" {
  224. reqInfoHandler(w, r)
  225. return
  226. }
  227. homeOldHTTP(w, r)
  228. return
  229. }
  230. mux2.ServeHTTP(w, r)
  231. })
  232. mux2.HandleFunc("/", home)
  233. mux2.Handle("/file/gopher.png", fileServer("https://golang.org/doc/gopher/frontpage.png", 0))
  234. mux2.Handle("/file/go.src.tar.gz", fileServer("https://storage.googleapis.com/golang/go1.4.1.src.tar.gz", 0))
  235. mux2.HandleFunc("/reqinfo", reqInfoHandler)
  236. mux2.HandleFunc("/crc32", crcHandler)
  237. mux2.HandleFunc("/ECHO", echoCapitalHandler)
  238. mux2.HandleFunc("/clockstream", clockStreamHandler)
  239. mux2.Handle("/gophertiles", tiles)
  240. mux2.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
  241. http.Redirect(w, r, "/", http.StatusFound)
  242. })
  243. stripHomedir := regexp.MustCompile(`/(Users|home)/\w+`)
  244. mux2.HandleFunc("/goroutines", func(w http.ResponseWriter, r *http.Request) {
  245. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  246. buf := make([]byte, 2<<20)
  247. w.Write(stripHomedir.ReplaceAll(buf[:runtime.Stack(buf, true)], nil))
  248. })
  249. }
  250. var pushResources = map[string]http.Handler{
  251. "/serverpush/static/jquery.min.js": fileServer("https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js", 100*time.Millisecond),
  252. "/serverpush/static/godocs.js": fileServer("https://golang.org/lib/godoc/godocs.js", 100*time.Millisecond),
  253. "/serverpush/static/playground.js": fileServer("https://golang.org/lib/godoc/playground.js", 100*time.Millisecond),
  254. "/serverpush/static/style.css": fileServer("https://golang.org/lib/godoc/style.css", 100*time.Millisecond),
  255. }
  256. func newPushHandler() http.Handler {
  257. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  258. for path, handler := range pushResources {
  259. if r.URL.Path == path {
  260. handler.ServeHTTP(w, r)
  261. return
  262. }
  263. }
  264. cacheBust := time.Now().UnixNano()
  265. if pusher, ok := w.(http.Pusher); ok {
  266. for path := range pushResources {
  267. url := fmt.Sprintf("%s?%d", path, cacheBust)
  268. if err := pusher.Push(url, nil); err != nil {
  269. log.Printf("Failed to push %v: %v", path, err)
  270. }
  271. }
  272. }
  273. time.Sleep(100 * time.Millisecond) // fake network latency + parsing time
  274. if err := pushTmpl.Execute(w, struct {
  275. CacheBust int64
  276. HTTPSHost string
  277. HTTPHost string
  278. }{
  279. CacheBust: cacheBust,
  280. HTTPSHost: httpsHost(),
  281. HTTPHost: httpHost(),
  282. }); err != nil {
  283. log.Printf("Executing server push template: %v", err)
  284. }
  285. })
  286. }
  287. func newGopherTilesHandler() http.Handler {
  288. const gopherURL = "https://blog.golang.org/go-programming-language-turns-two_gophers.jpg"
  289. res, err := http.Get(gopherURL)
  290. if err != nil {
  291. log.Fatal(err)
  292. }
  293. if res.StatusCode != 200 {
  294. log.Fatalf("Error fetching %s: %v", gopherURL, res.Status)
  295. }
  296. slurp, err := ioutil.ReadAll(res.Body)
  297. res.Body.Close()
  298. if err != nil {
  299. log.Fatal(err)
  300. }
  301. im, err := jpeg.Decode(bytes.NewReader(slurp))
  302. if err != nil {
  303. if len(slurp) > 1024 {
  304. slurp = slurp[:1024]
  305. }
  306. log.Fatalf("Failed to decode gopher image: %v (got %q)", err, slurp)
  307. }
  308. type subImager interface {
  309. SubImage(image.Rectangle) image.Image
  310. }
  311. const tileSize = 32
  312. xt := im.Bounds().Max.X / tileSize
  313. yt := im.Bounds().Max.Y / tileSize
  314. var tile [][][]byte // y -> x -> jpeg bytes
  315. for yi := 0; yi < yt; yi++ {
  316. var row [][]byte
  317. for xi := 0; xi < xt; xi++ {
  318. si := im.(subImager).SubImage(image.Rectangle{
  319. Min: image.Point{xi * tileSize, yi * tileSize},
  320. Max: image.Point{(xi + 1) * tileSize, (yi + 1) * tileSize},
  321. })
  322. buf := new(bytes.Buffer)
  323. if err := jpeg.Encode(buf, si, &jpeg.Options{Quality: 90}); err != nil {
  324. log.Fatal(err)
  325. }
  326. row = append(row, buf.Bytes())
  327. }
  328. tile = append(tile, row)
  329. }
  330. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  331. ms, _ := strconv.Atoi(r.FormValue("latency"))
  332. const nanosPerMilli = 1e6
  333. if r.FormValue("x") != "" {
  334. x, _ := strconv.Atoi(r.FormValue("x"))
  335. y, _ := strconv.Atoi(r.FormValue("y"))
  336. if ms <= 1000 {
  337. time.Sleep(time.Duration(ms) * nanosPerMilli)
  338. }
  339. if x >= 0 && x < xt && y >= 0 && y < yt {
  340. http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(tile[y][x]))
  341. return
  342. }
  343. }
  344. io.WriteString(w, "<html><body onload='showtimes()'>")
  345. fmt.Fprintf(w, "A grid of %d tiled images is below. Compare:<p>", xt*yt)
  346. for _, ms := range []int{0, 30, 200, 1000} {
  347. d := time.Duration(ms) * nanosPerMilli
  348. 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",
  349. httpsHost(), ms, d,
  350. httpHost(), ms, d,
  351. )
  352. }
  353. io.WriteString(w, "<p>\n")
  354. cacheBust := time.Now().UnixNano()
  355. for y := 0; y < yt; y++ {
  356. for x := 0; x < xt; x++ {
  357. fmt.Fprintf(w, "<img width=%d height=%d src='/gophertiles?x=%d&y=%d&cachebust=%d&latency=%d'>",
  358. tileSize, tileSize, x, y, cacheBust, ms)
  359. }
  360. io.WriteString(w, "<br/>\n")
  361. }
  362. io.WriteString(w, `<p><div id='loadtimes'></div></p>
  363. <script>
  364. function showtimes() {
  365. var times = 'Times from connection start:<br>'
  366. times += 'DOM loaded: ' + (window.performance.timing.domContentLoadedEventEnd - window.performance.timing.connectStart) + 'ms<br>'
  367. times += 'DOM complete (images loaded): ' + (window.performance.timing.domComplete - window.performance.timing.connectStart) + 'ms<br>'
  368. document.getElementById('loadtimes').innerHTML = times
  369. }
  370. </script>
  371. <hr><a href='/'>&lt;&lt Back to Go HTTP/2 demo server</a></body></html>`)
  372. })
  373. }
  374. func httpsHost() string {
  375. if *hostHTTPS != "" {
  376. return *hostHTTPS
  377. }
  378. if v := *httpsAddr; strings.HasPrefix(v, ":") {
  379. return "localhost" + v
  380. } else {
  381. return v
  382. }
  383. }
  384. func httpHost() string {
  385. if *hostHTTP != "" {
  386. return *hostHTTP
  387. }
  388. if v := *httpAddr; strings.HasPrefix(v, ":") {
  389. return "localhost" + v
  390. } else {
  391. return v
  392. }
  393. }
  394. func serveProdTLS(autocertManager *autocert.Manager) error {
  395. srv := &http.Server{
  396. TLSConfig: &tls.Config{
  397. GetCertificate: autocertManager.GetCertificate,
  398. },
  399. }
  400. http2.ConfigureServer(srv, &http2.Server{
  401. NewWriteScheduler: func() http2.WriteScheduler {
  402. return http2.NewPriorityWriteScheduler(nil)
  403. },
  404. })
  405. ln, err := net.Listen("tcp", ":443")
  406. if err != nil {
  407. return err
  408. }
  409. return srv.Serve(tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, srv.TLSConfig))
  410. }
  411. type tcpKeepAliveListener struct {
  412. *net.TCPListener
  413. }
  414. func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
  415. tc, err := ln.AcceptTCP()
  416. if err != nil {
  417. return
  418. }
  419. tc.SetKeepAlive(true)
  420. tc.SetKeepAlivePeriod(3 * time.Minute)
  421. return tc, nil
  422. }
  423. func serveProd() error {
  424. log.Printf("running in production mode")
  425. storageClient, err := storage.NewClient(context.Background())
  426. if err != nil {
  427. log.Fatalf("storage.NewClient: %v", err)
  428. }
  429. autocertManager := &autocert.Manager{
  430. Prompt: autocert.AcceptTOS,
  431. HostPolicy: autocert.HostWhitelist("http2.golang.org"),
  432. Cache: autocertcache.NewGoogleCloudStorageCache(storageClient, "golang-h2demo-autocert"),
  433. }
  434. errc := make(chan error, 2)
  435. go func() { errc <- http.ListenAndServe(":80", autocertManager.HTTPHandler(http.DefaultServeMux)) }()
  436. go func() { errc <- serveProdTLS(autocertManager) }()
  437. return <-errc
  438. }
  439. const idleTimeout = 5 * time.Minute
  440. const activeTimeout = 10 * time.Minute
  441. // TODO: put this into the standard library and actually send
  442. // PING frames and GOAWAY, etc: golang.org/issue/14204
  443. func idleTimeoutHook() func(net.Conn, http.ConnState) {
  444. var mu sync.Mutex
  445. m := map[net.Conn]*time.Timer{}
  446. return func(c net.Conn, cs http.ConnState) {
  447. mu.Lock()
  448. defer mu.Unlock()
  449. if t, ok := m[c]; ok {
  450. delete(m, c)
  451. t.Stop()
  452. }
  453. var d time.Duration
  454. switch cs {
  455. case http.StateNew, http.StateIdle:
  456. d = idleTimeout
  457. case http.StateActive:
  458. d = activeTimeout
  459. default:
  460. return
  461. }
  462. m[c] = time.AfterFunc(d, func() {
  463. log.Printf("closing idle conn %v after %v", c.RemoteAddr(), d)
  464. go c.Close()
  465. })
  466. }
  467. }
  468. func main() {
  469. var srv http.Server
  470. flag.BoolVar(&http2.VerboseLogs, "verbose", false, "Verbose HTTP/2 debugging.")
  471. flag.Parse()
  472. srv.Addr = *httpsAddr
  473. srv.ConnState = idleTimeoutHook()
  474. registerHandlers()
  475. if *prod {
  476. *hostHTTP = "http2.golang.org"
  477. *hostHTTPS = "http2.golang.org"
  478. log.Fatal(serveProd())
  479. }
  480. url := "https://" + httpsHost() + "/"
  481. log.Printf("Listening on " + url)
  482. http2.ConfigureServer(&srv, &http2.Server{})
  483. if *httpAddr != "" {
  484. go func() {
  485. log.Printf("Listening on http://" + httpHost() + "/ (for unencrypted HTTP/1)")
  486. log.Fatal(http.ListenAndServe(*httpAddr, nil))
  487. }()
  488. }
  489. go func() {
  490. log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
  491. }()
  492. select {}
  493. }