h2demo.go 15 KB

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