gzip doesn't work
mostafasolati opened this issue · 6 comments
After enabling this middleware browser downloads page! and I can't see result in browser
Have the same issue :/ Would love to use this
@mostafasolati @MTRNord it's work for me. Could you post your example code?
Hi my code is basicly (non functioning but you get the point what it does I think. Otherwise feel free to ask):
router := gin.Default()
router.Use(gzip.Gzip(gzip.DefaultCompression))
router.GET("/login", func (c *gin.Context) {
templates.WritePageTemplate(c.Writer, &templates.LoginPage{
Link: "something",
})
})
A bit of explanation for the above: The templates.WritePageTemplate()
function comes from https://github.com/valyala/quicktemplate and generates HTML via go files.
I expect to get a HTML file as I do without gzip but what happens is the following response and getting a download of a file named "document.gzip"
Response Headers (via chrome Network Tab):
Content-Encoding:gzip
Content-Length:239
Content-Type:application/x-gzip
Date:Wed, 02 Aug 2017 18:59:55 GMT
Vary:Accept-Encoding
@MTRNord @mostafasolati because net/http
will detect contentType
header if you don't to set. And you use quicktemplate which is not to set contentType, so you have to specify response header like:
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
"github.com/valyala/quicktemplate/examples/basicserver/templates"
)
func main() {
r := gin.Default()
r.Use(gzip.Gzip(gzip.DefaultCompression))
r.GET("/quick-template", func(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "text/html; charset=utf-8") // You have to set 'Content-Type'
templates.WritePageTemplate(c.Writer, &templates.BasePage{})
})
// or you can use c.HTML, it will set Content-Type
r.LoadHTMLFiles("templates/template.html")
r.GET("/gin", func(c *gin.Context) {
c.HTML(http.StatusOK, "template.html", gin.H{"values": fmt.Sprint(time.Now().Unix())})
})
// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}
Test:
$ curl -v -H "Accept-Encoding: gzip" http://localhost:8080/quick-template
Will Output like:
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /quick-template HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.51.0
> Accept: */*
> Accept-Encoding: gzip
>
< HTTP/1.1 200 OK
< Content-Encoding: gzip
< Content-Type: text/html; charset=utf-8
< Vary: Accept-Encoding
< Date: Sun, 06 Aug 2017 08:23:02 GMT
< Content-Length: 133
<
Ah ok thanks :) I will do so :D
Can we close this now?