golang.org/toolchain@v0.0.1-go1.9rc2.windows-amd64/blog/content/h2push/server/main.go (about)

     1  // Copyright 2017 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  
     5  // +build go1.8
     6  
     7  // The server command demonstrates a server with HTTP/2 Server Push support.
     8  package main
     9  
    10  import (
    11  	"flag"
    12  	"fmt"
    13  	"log"
    14  	"net/http"
    15  )
    16  
    17  var httpAddr = flag.String("http", ":8080", "Listen address")
    18  
    19  func main() {
    20  	flag.Parse()
    21  	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
    22  	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    23  		if r.URL.Path != "/" {
    24  			http.NotFound(w, r)
    25  			return
    26  		}
    27  		pusher, ok := w.(http.Pusher)
    28  		if ok {
    29  			// Push is supported. Try pushing rather than
    30  			// waiting for the browser request these static assets.
    31  			if err := pusher.Push("/static/app.js", nil); err != nil {
    32  				log.Printf("Failed to push: %v", err)
    33  			}
    34  			if err := pusher.Push("/static/style.css", nil); err != nil {
    35  				log.Printf("Failed to push: %v", err)
    36  			}
    37  		}
    38  		fmt.Fprintf(w, indexHTML)
    39  	})
    40  	log.Fatal(http.ListenAndServeTLS(*httpAddr, "cert.pem", "key.pem", nil))
    41  }
    42  
    43  const indexHTML = `<html>
    44  <head>
    45  	<title>Hello World</title>
    46  	<script src="/static/app.js"></script>
    47  	<link rel="stylesheet" href="/static/style.css"">
    48  </head>
    49  <body>
    50  Hello, gopher!
    51  </body>
    52  </html>
    53  `