Add Pusher() function for support http2 server push (#1273)
gin already support http2, while previously not support server push. Add Pusher() function to extend the ResponseWriter interface. ```golang // get http.Pusher if pusher := c.Writer.Pusher(); pusher != nil { // use pusher.Push() to do server push } ``` <img width="881" alt="screen shot 2018-03-07 at 11 20 49 pm" src="https://user-images.githubusercontent.com/16014993/37100619-680c00c6-225e-11e8-9352-76ec3bd62894.png">
This commit is contained in:
50
README.md
50
README.md
@ -54,6 +54,7 @@ Gin is a web framework written in Go (Golang). It features a martini-like API wi
|
||||
- [Build a single binary with templates](#build-a-single-binary-with-templates)
|
||||
- [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct)
|
||||
- [Try to bind body into different structs](#try-to-bind-body-into-different-structs)
|
||||
- [http2 server push](#http2-server-push)
|
||||
- [Testing](#testing)
|
||||
- [Users](#users--)
|
||||
|
||||
@ -1656,6 +1657,55 @@ enough to call binding at once.
|
||||
can be called by `c.ShouldBind()` multiple times without any damage to
|
||||
performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).
|
||||
|
||||
### http2 server push
|
||||
|
||||
http.Pusher is supported only **go1.8+**. See the [golang blog](https://blog.golang.org/h2push) for detail information.
|
||||
|
||||
[embedmd]:# (examples/http-pusher/main.go go)
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"log"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var html = template.Must(template.New("https").Parse(`
|
||||
<html>
|
||||
<head>
|
||||
<title>Https Test</title>
|
||||
<script src="/assets/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<h1 style="color:red;">Welcome, Ginner!</h1>
|
||||
</body>
|
||||
</html>
|
||||
`))
|
||||
|
||||
func main() {
|
||||
r := gin.Default()
|
||||
r.Static("/assets", "./assets")
|
||||
r.SetHTMLTemplate(html)
|
||||
|
||||
r.GET("/", func(c *gin.Context) {
|
||||
if pusher := c.Writer.Pusher(); pusher != nil {
|
||||
// use pusher.Push() to do server push
|
||||
if err := pusher.Push("/assets/app.js", nil); err != nil {
|
||||
log.Printf("Failed to push: %v", err)
|
||||
}
|
||||
}
|
||||
c.HTML(200, "https", gin.H{
|
||||
"status": "success",
|
||||
})
|
||||
})
|
||||
|
||||
// Listen and Server in https://127.0.0.1:8080
|
||||
r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")
|
||||
}
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
The `net/http/httptest` package is preferable way for HTTP testing.
|
||||
|
Reference in New Issue
Block a user