h2demo.go 14 KB

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