http2 server push

http.Pusher is supported only go1.8+. See the golang blog for detail information.

  1. package main
  2. import (
  3. "html/template"
  4. "log"
  5. "github.com/gin-gonic/gin"
  6. )
  7. var html = template.Must(template.New("https").Parse(`
  8. <html>
  9. <head>
  10. <title>Https Test</title>
  11. <script src="/assets/app.js"></script>
  12. </head>
  13. <body>
  14. <h1 style="color:red;">Welcome, Ginner!</h1>
  15. </body>
  16. </html>
  17. `))
  18. func main() {
  19. r := gin.Default()
  20. r.Static("/assets", "./assets")
  21. r.SetHTMLTemplate(html)
  22. r.GET("/", func(c *gin.Context) {
  23. if pusher := c.Writer.Pusher(); pusher != nil {
  24. // use pusher.Push() to do server push
  25. if err := pusher.Push("/assets/app.js", nil); err != nil {
  26. log.Printf("Failed to push: %v", err)
  27. }
  28. }
  29. c.HTML(200, "https", gin.H{
  30. "status": "success",
  31. })
  32. })
  33. // Listen and Server in https://127.0.0.1:8080
  34. r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")
  35. }