h2demo.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. package main
  6. import (
  7. "bytes"
  8. "crypto/tls"
  9. "flag"
  10. "fmt"
  11. "hash/crc32"
  12. "io"
  13. "io/ioutil"
  14. "log"
  15. "net"
  16. "net/http"
  17. "os/exec"
  18. "path"
  19. "runtime"
  20. "strings"
  21. "sync"
  22. "time"
  23. "camlistore.org/pkg/googlestorage"
  24. "camlistore.org/pkg/singleflight"
  25. "github.com/bradfitz/http2"
  26. )
  27. var (
  28. openFirefox = flag.Bool("openff", false, "Open Firefox")
  29. prod = flag.Bool("prod", false, "Whether to configure itself to be the production http2.golang.org server.")
  30. )
  31. func homeOldHTTP(w http.ResponseWriter, r *http.Request) {
  32. io.WriteString(w, `<html>
  33. <body>
  34. <h1>Go + HTTP/2</h1>
  35. <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>
  36. <p>Unfortunately, you're <b>not</b> using HTTP/2 right now.</p>
  37. <p>See code & instructions for connecting at <a href="https://github.com/bradfitz/http2">https://github.com/bradfitz/http2</a>.</p>
  38. </body></html>`)
  39. }
  40. func home(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
  45. href="https://http2.github.io/">HTTP/2</a> demo & interop server.</p>
  46. <p>Congratulations, <b>you're using HTTP/2 right now</b>.</p>
  47. <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>
  48. <p> The code is currently at <a
  49. href="https://github.com/bradfitz/http2">github.com/bradfitz/http2</a>
  50. but will move to the Go standard library at some point in the future
  51. (enabled by default, without users needing to change their code).</p>
  52. <p>Contact info: <i>bradfitz@golang.org</i>, or <a
  53. href="https://github.com/bradfitz/http2/issues">file a bug</a>.</p>
  54. <h2>Handlers for testing</h2>
  55. <ul>
  56. <li>GET <a href="/reqinfo">/reqinfo</a> to dump the request + headers received</li>
  57. <li>GET <a href="/clockstream">/clockstream</a> streams the current time every second</li>
  58. <li>GET <a href="/file/gopher.png">/file/gopher.png</a> for a small file (does If-Modified-Since, Content-Range, etc)</li>
  59. <li>GET <a href="/file/go.src.tar.gz">/file/go.src.tar.gz</a> for a larger file (~10 MB)</li>
  60. <li>GET <a href="/redirect">/redirect</a> to redirect back to / (this page)</li>
  61. <li>PUT something to <a href="/crc32">/crc32</a> to get a count of number of bytes and its CRC-32</li>
  62. </ul>
  63. </body></html>`)
  64. }
  65. func reqInfoHandler(w http.ResponseWriter, r *http.Request) {
  66. w.Header().Set("Content-Type", "text/plain")
  67. fmt.Fprintf(w, "Method: %s\n", r.Method)
  68. fmt.Fprintf(w, "Protocol: %s\n", r.Proto)
  69. fmt.Fprintf(w, "Host: %s\n", r.Host)
  70. fmt.Fprintf(w, "RemoteAddr: %s\n", r.RemoteAddr)
  71. fmt.Fprintf(w, "RequestURI: %q\n", r.RequestURI)
  72. fmt.Fprintf(w, "URL: %#v\n", r.URL)
  73. fmt.Fprintf(w, "Body.ContentLength: %d (-1 means unknown)\n", r.ContentLength)
  74. fmt.Fprintf(w, "Close: %v (relevant for HTTP/1 only)\n", r.Close)
  75. fmt.Fprintf(w, "TLS: %#v\n", r.TLS)
  76. fmt.Fprintf(w, "\nHeaders:\n")
  77. r.Header.Write(w)
  78. }
  79. func crcHandler(w http.ResponseWriter, r *http.Request) {
  80. if r.Method != "PUT" {
  81. http.Error(w, "PUT required.", 400)
  82. return
  83. }
  84. crc := crc32.NewIEEE()
  85. n, err := io.Copy(crc, r.Body)
  86. if err == nil {
  87. w.Header().Set("Content-Type", "text/plain")
  88. fmt.Fprintf(w, "bytes=%d, CRC32=%x", n, crc.Sum(nil))
  89. }
  90. }
  91. var (
  92. fsGrp singleflight.Group
  93. fsMu sync.Mutex // guards fsCache
  94. fsCache = map[string]http.Handler{}
  95. )
  96. // fileServer returns a file-serving handler that proxies URL.
  97. // It lazily fetches URL on the first access and caches its contents forever.
  98. func fileServer(url string) http.Handler {
  99. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  100. hi, err := fsGrp.Do(url, func() (interface{}, error) {
  101. fsMu.Lock()
  102. if h, ok := fsCache[url]; ok {
  103. fsMu.Unlock()
  104. return h, nil
  105. }
  106. fsMu.Unlock()
  107. res, err := http.Get(url)
  108. if err != nil {
  109. return nil, err
  110. }
  111. defer res.Body.Close()
  112. slurp, err := ioutil.ReadAll(res.Body)
  113. if err != nil {
  114. return nil, err
  115. }
  116. modTime := time.Now()
  117. var h http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  118. http.ServeContent(w, r, path.Base(url), modTime, bytes.NewReader(slurp))
  119. })
  120. fsMu.Lock()
  121. fsCache[url] = h
  122. fsMu.Unlock()
  123. return h, nil
  124. })
  125. if err != nil {
  126. http.Error(w, err.Error(), 500)
  127. return
  128. }
  129. hi.(http.Handler).ServeHTTP(w, r)
  130. })
  131. }
  132. func clockStreamHandler(w http.ResponseWriter, r *http.Request) {
  133. clientGone := w.(http.CloseNotifier).CloseNotify()
  134. w.Header().Set("Content-Type", "text/plain")
  135. ticker := time.NewTicker(1 * time.Second)
  136. defer ticker.Stop()
  137. fmt.Fprintf(w, "# ~1KB of junk to force browsers to start rendering immediately: \n")
  138. io.WriteString(w, strings.Repeat("# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n", 13))
  139. for {
  140. fmt.Fprintf(w, "%v\n", time.Now())
  141. w.(http.Flusher).Flush()
  142. select {
  143. case <-ticker.C:
  144. case <-clientGone:
  145. log.Printf("Client %v disconnected from the clock", r.RemoteAddr)
  146. return
  147. }
  148. }
  149. }
  150. func registerHandlers() {
  151. mux2 := http.NewServeMux()
  152. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  153. if r.TLS == nil {
  154. http.Redirect(w, r, "https://http2.golang.org/", http.StatusFound)
  155. return
  156. }
  157. if r.ProtoMajor == 1 {
  158. if r.URL.Path == "/reqinfo" {
  159. reqInfoHandler(w, r)
  160. } else {
  161. homeOldHTTP(w, r)
  162. }
  163. return
  164. }
  165. mux2.ServeHTTP(w, r)
  166. })
  167. mux2.HandleFunc("/", home)
  168. mux2.Handle("/file/gopher.png", fileServer("https://golang.org/doc/gopher/frontpage.png"))
  169. mux2.Handle("/file/go.src.tar.gz", fileServer("https://storage.googleapis.com/golang/go1.4rc1.src.tar.gz"))
  170. mux2.HandleFunc("/reqinfo", reqInfoHandler)
  171. mux2.HandleFunc("/crc32", crcHandler)
  172. mux2.HandleFunc("/clockstream", clockStreamHandler)
  173. mux2.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
  174. http.Redirect(w, r, "/", http.StatusFound)
  175. })
  176. }
  177. func serveProdTLS() error {
  178. c, err := googlestorage.NewServiceClient()
  179. if err != nil {
  180. return err
  181. }
  182. slurp := func(key string) ([]byte, error) {
  183. const bucket = "http2-demo-server-tls"
  184. rc, _, err := c.GetObject(&googlestorage.Object{
  185. Bucket: bucket,
  186. Key: key,
  187. })
  188. if err != nil {
  189. return nil, fmt.Errorf("Error fetching GCS object %q in bucket %q: %v", key, bucket, err)
  190. }
  191. defer rc.Close()
  192. return ioutil.ReadAll(rc)
  193. }
  194. certPem, err := slurp("http2.golang.org.chained.pem")
  195. if err != nil {
  196. return err
  197. }
  198. keyPem, err := slurp("http2.golang.org.key")
  199. if err != nil {
  200. return err
  201. }
  202. cert, err := tls.X509KeyPair(certPem, keyPem)
  203. if err != nil {
  204. return err
  205. }
  206. srv := &http.Server{
  207. TLSConfig: &tls.Config{
  208. Certificates: []tls.Certificate{cert},
  209. },
  210. }
  211. http2.ConfigureServer(srv, &http2.Server{})
  212. ln, err := net.Listen("tcp", ":443")
  213. if err != nil {
  214. return err
  215. }
  216. return srv.Serve(tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, srv.TLSConfig))
  217. }
  218. type tcpKeepAliveListener struct {
  219. *net.TCPListener
  220. }
  221. func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
  222. tc, err := ln.AcceptTCP()
  223. if err != nil {
  224. return
  225. }
  226. tc.SetKeepAlive(true)
  227. tc.SetKeepAlivePeriod(3 * time.Minute)
  228. return tc, nil
  229. }
  230. func serveProd() error {
  231. errc := make(chan error, 2)
  232. go func() { errc <- http.ListenAndServe(":80", nil) }()
  233. go func() { errc <- serveProdTLS() }()
  234. return <-errc
  235. }
  236. func main() {
  237. var srv http.Server
  238. flag.BoolVar(&http2.VerboseLogs, "verbose", false, "Verbose HTTP/2 debugging.")
  239. flag.StringVar(&srv.Addr, "addr", "localhost:4430", "host:port to listen on ")
  240. flag.Parse()
  241. registerHandlers()
  242. if *prod {
  243. log.Fatal(serveProd())
  244. }
  245. url := "https://" + srv.Addr + "/"
  246. log.Printf("Listening on " + url)
  247. http2.ConfigureServer(&srv, &http2.Server{})
  248. go func() {
  249. log.Fatal(srv.ListenAndServeTLS("server.crt", "server.key"))
  250. }()
  251. if *openFirefox && runtime.GOOS == "darwin" {
  252. time.Sleep(250 * time.Millisecond)
  253. exec.Command("open", "-b", "org.mozilla.nightly", "https://localhost:4430/").Run()
  254. }
  255. select {}
  256. }