h2demo.go 13 KB

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