1
0
mirror of https://github.com/astaxie/beego.git synced 2024-12-22 23:40:50 +00:00

support gzip #37

This commit is contained in:
astaxie 2013-04-18 23:13:53 +08:00
parent a3f8fd6a77
commit 140b513c7b
2 changed files with 42 additions and 3 deletions

View File

@ -37,6 +37,7 @@ var (
SessionSavePath string // session savepath if use mysql/redis/file this set to the connectinfo
UseFcgi bool
MaxMemory int64
EnableGzip bool // enable gzip
GlobalSessions *session.Manager //GlobalSessions
)
@ -66,6 +67,7 @@ func init() {
SessionSavePath = ""
UseFcgi = false
MaxMemory = 1 << 26 //64MB
EnableGzip = false
} else {
HttpAddr = AppConfig.String("httpaddr")
if v, err := AppConfig.Int("httpport"); err != nil {
@ -135,6 +137,11 @@ func init() {
} else {
UseFcgi = ar
}
if ar, err := AppConfig.Bool("enablegzip"); err != nil {
EnableGzip = false
} else {
EnableGzip = ar
}
}
StaticDir["/static"] = "static"

View File

@ -2,6 +2,8 @@ package beego
import (
"bytes"
"compress/gzip"
"compress/zlib"
"encoding/json"
"encoding/xml"
"github.com/astaxie/beego/session"
@ -91,9 +93,39 @@ func (c *Controller) Render() error {
if err != nil {
return err
} else {
c.Ctx.SetHeader("Content-Length", strconv.Itoa(len(rb)), true)
c.Ctx.ContentType("text/html")
c.Ctx.ResponseWriter.Write(rb)
c.Ctx.ResponseWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
output_writer := c.Ctx.ResponseWriter.(io.Writer)
if EnableGzip == true && c.Ctx.Request.Header.Get("Accept-Encoding") != "" {
splitted := strings.SplitN(c.Ctx.Request.Header.Get("Accept-Encoding"), ",", -1)
encodings := make([]string, len(splitted))
for i, val := range splitted {
encodings[i] = strings.TrimSpace(val)
}
for _, val := range encodings {
if val == "gzip" {
c.Ctx.ResponseWriter.Header().Set("Content-Encoding", "gzip")
output_writer, _ = gzip.NewWriterLevel(c.Ctx.ResponseWriter, gzip.BestSpeed)
break
} else if val == "deflate" {
c.Ctx.ResponseWriter.Header().Set("Content-Encoding", "deflate")
output_writer, _ = zlib.NewWriterLevel(c.Ctx.ResponseWriter, zlib.BestSpeed)
break
}
}
} else {
c.Ctx.SetHeader("Content-Length", strconv.Itoa(len(rb)), true)
}
output_writer.Write(rb)
switch output_writer.(type) {
case *gzip.Writer:
output_writer.(*gzip.Writer).Close()
case *zlib.Writer:
output_writer.(*zlib.Writer).Close()
case io.WriteCloser:
output_writer.(io.WriteCloser).Close()
}
return nil
}
return nil