1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 19:20:59 +00:00

Merge pull request #1376 from JessonChan/develop

static file code refactor and bug fixed
This commit is contained in:
astaxie 2015-11-08 23:21:16 +08:00
commit 9b725c73c3
4 changed files with 109 additions and 110 deletions

View File

@ -523,18 +523,19 @@ func ParseConfig() (err error) {
if sgz := AppConfig.String("StaticExtensionsToGzip"); sgz != "" { if sgz := AppConfig.String("StaticExtensionsToGzip"); sgz != "" {
extensions := strings.Split(sgz, ",") extensions := strings.Split(sgz, ",")
if len(extensions) > 0 { fileExts := []string{}
StaticExtensionsToGzip = []string{}
for _, ext := range extensions { for _, ext := range extensions {
if len(ext) == 0 { ext = strings.TrimSpace(ext)
if ext == "" {
continue continue
} }
extWithDot := ext if !strings.HasPrefix(ext, ".") {
if extWithDot[:1] != "." { ext = "." + ext
extWithDot = "." + extWithDot
} }
StaticExtensionsToGzip = append(StaticExtensionsToGzip, extWithDot) fileExts = append(fileExts, ext)
} }
if len(fileExts) > 0 {
StaticExtensionsToGzip = fileExts
} }
} }

View File

@ -103,22 +103,10 @@ func (output *BeegoOutput) Cookie(name string, value string, others ...interface
//fix cookie not work in IE //fix cookie not work in IE
if len(others) > 0 { if len(others) > 0 {
switch v := others[0].(type) { switch v := others[0].(type) {
case int: case int, int32, int64:
if v > 0 { if v > 0 {
fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(v)*time.Second).UTC().Format(time.RFC1123), v) fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(v)*time.Second).UTC().Format(time.RFC1123), v)
} else if v < 0 { } else if v <= 0 {
fmt.Fprintf(&b, "; Max-Age=0")
}
case int64:
if v > 0 {
fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(v)*time.Second).UTC().Format(time.RFC1123), v)
} else if v < 0 {
fmt.Fprintf(&b, "; Max-Age=0")
}
case int32:
if v > 0 {
fmt.Fprintf(&b, "; Expires=%s; Max-Age=%d", time.Now().Add(time.Duration(v)*time.Second).UTC().Format(time.RFC1123), v)
} else if v < 0 {
fmt.Fprintf(&b, "; Max-Age=0") fmt.Fprintf(&b, "; Max-Age=0")
} }
} }

View File

@ -29,72 +29,72 @@ import (
) )
var ( var (
gmfim = make(map[string]*memFileInfo) menFileInfoMap = make(map[string]*memFileInfo)
lock sync.RWMutex lock sync.RWMutex
) )
// OpenMemZipFile returns MemFile object with a compressed static file. // openMemZipFile returns MemFile object with a compressed static file.
// it's used for serve static file if gzip enable. // it's used for serve static file if gzip enable.
func openMemZipFile(path string, zip string) (*memFile, error) { func openMemZipFile(path string, zip string) (*memFile, error) {
osfile, e := os.Open(path) osFile, e := os.Open(path)
if e != nil { if e != nil {
return nil, e return nil, e
} }
defer osfile.Close() defer osFile.Close()
osfileinfo, e := osfile.Stat() osFileInfo, e := osFile.Stat()
if e != nil { if e != nil {
return nil, e return nil, e
} }
modtime := osfileinfo.ModTime() modTime := osFileInfo.ModTime()
fileSize := osfileinfo.Size() fileSize := osFileInfo.Size()
lock.RLock() lock.RLock()
cfi, ok := gmfim[zip+":"+path] cfi, ok := menFileInfoMap[zip+":"+path]
lock.RUnlock() lock.RUnlock()
if !(ok && cfi.ModTime() == modtime && cfi.fileSize == fileSize) { if !(ok && cfi.ModTime() == modTime && cfi.fileSize == fileSize) {
var content []byte var content []byte
if zip == "gzip" { if zip == "gzip" {
var zipbuf bytes.Buffer var zipBuf bytes.Buffer
gzipwriter, e := gzip.NewWriterLevel(&zipbuf, gzip.BestCompression) gzipWriter, e := gzip.NewWriterLevel(&zipBuf, gzip.BestCompression)
if e != nil { if e != nil {
return nil, e return nil, e
} }
_, e = io.Copy(gzipwriter, osfile) _, e = io.Copy(gzipWriter, osFile)
gzipwriter.Close() gzipWriter.Close()
if e != nil { if e != nil {
return nil, e return nil, e
} }
content, e = ioutil.ReadAll(&zipbuf) content, e = ioutil.ReadAll(&zipBuf)
if e != nil { if e != nil {
return nil, e return nil, e
} }
} else if zip == "deflate" { } else if zip == "deflate" {
var zipbuf bytes.Buffer var zipBuf bytes.Buffer
deflatewriter, e := flate.NewWriter(&zipbuf, flate.BestCompression) deflateWriter, e := flate.NewWriter(&zipBuf, flate.BestCompression)
if e != nil { if e != nil {
return nil, e return nil, e
} }
_, e = io.Copy(deflatewriter, osfile) _, e = io.Copy(deflateWriter, osFile)
deflatewriter.Close() deflateWriter.Close()
if e != nil { if e != nil {
return nil, e return nil, e
} }
content, e = ioutil.ReadAll(&zipbuf) content, e = ioutil.ReadAll(&zipBuf)
if e != nil { if e != nil {
return nil, e return nil, e
} }
} else { } else {
content, e = ioutil.ReadAll(osfile) content, e = ioutil.ReadAll(osFile)
if e != nil { if e != nil {
return nil, e return nil, e
} }
} }
cfi = &memFileInfo{osfileinfo, modtime, content, int64(len(content)), fileSize} cfi = &memFileInfo{osFileInfo, modTime, content, int64(len(content)), fileSize}
lock.Lock() lock.Lock()
defer lock.Unlock() defer lock.Unlock()
gmfim[zip+":"+path] = cfi menFileInfoMap[zip+":"+path] = cfi
} }
return &memFile{fi: cfi, offset: 0}, nil return &memFile{fi: cfi, offset: 0}, nil
} }
@ -139,7 +139,7 @@ func (fi *memFileInfo) Sys() interface{} {
return nil return nil
} }
// MemFile contains MemFileInfo and bytes offset when reading. // memFile contains MemFileInfo and bytes offset when reading.
// it implements io.Reader,io.ReadCloser and io.Seeker. // it implements io.Reader,io.ReadCloser and io.Seeker.
type memFile struct { type memFile struct {
fi *memFileInfo fi *memFileInfo
@ -198,7 +198,7 @@ func (f *memFile) Seek(offset int64, whence int) (ret int64, err error) {
return f.offset, nil return f.offset, nil
} }
// GetAcceptEncodingZip returns accept encoding format in http header. // getAcceptEncodingZip returns accept encoding format in http header.
// zip is first, then deflate if both accepted. // zip is first, then deflate if both accepted.
// If no accepted, return empty string. // If no accepted, return empty string.
func getAcceptEncodingZip(r *http.Request) string { func getAcceptEncodingZip(r *http.Request) string {

View File

@ -31,81 +31,95 @@ func serverStaticRouter(ctx *context.Context) {
return return
} }
requestPath := filepath.Clean(ctx.Input.Request.URL.Path) requestPath := filepath.Clean(ctx.Input.Request.URL.Path)
i := 0
for prefix, staticDir := range StaticDir { // special processing : favicon.ico/robots.txt can be in any static dir
if len(prefix) == 0 {
continue
}
if requestPath == "/favicon.ico" || requestPath == "/robots.txt" { if requestPath == "/favicon.ico" || requestPath == "/robots.txt" {
file := path.Join(".", requestPath)
if utils.FileExists(file) {
http.ServeFile(ctx.ResponseWriter, ctx.Request, file)
return
}
for _, staticDir := range StaticDir {
file := path.Join(staticDir, requestPath) file := path.Join(staticDir, requestPath)
if utils.FileExists(file) { if utils.FileExists(file) {
http.ServeFile(ctx.ResponseWriter, ctx.Request, file) http.ServeFile(ctx.ResponseWriter, ctx.Request, file)
return return
} }
i++ }
if i == len(StaticDir) {
http.NotFound(ctx.ResponseWriter, ctx.Request) http.NotFound(ctx.ResponseWriter, ctx.Request)
return return
} }
for prefix, staticDir := range StaticDir {
if len(prefix) == 0 {
continue continue
} }
if strings.HasPrefix(requestPath, prefix) { if strings.HasPrefix(requestPath, prefix) {
if len(requestPath) > len(prefix) && requestPath[len(prefix)] != '/' { if len(requestPath) > len(prefix) && requestPath[len(prefix)] != '/' {
continue continue
} }
file := path.Join(staticDir, requestPath[len(prefix):]) filePath := path.Join(staticDir, requestPath[len(prefix):])
finfo, err := os.Stat(file) fileInfo, err := os.Stat(filePath)
if err != nil { if err != nil {
if RunMode == "dev" { if RunMode == "dev" {
Warn("Can't find the file:", file, err) Warn("Can't find the file:", filePath, err)
} }
http.NotFound(ctx.ResponseWriter, ctx.Request) http.NotFound(ctx.ResponseWriter, ctx.Request)
return return
} }
//if the request is dir and DirectoryIndex is false then //if the request is dir and DirectoryIndex is false then
if finfo.IsDir() { if fileInfo.IsDir() {
if !DirectoryIndex { if !DirectoryIndex {
exception("403", ctx) exception("403", ctx)
return return
} else if ctx.Input.Request.URL.Path[len(ctx.Input.Request.URL.Path)-1] != '/' { }
if ctx.Input.Request.URL.Path[len(ctx.Input.Request.URL.Path)-1] != '/' {
http.Redirect(ctx.ResponseWriter, ctx.Request, ctx.Input.Request.URL.Path+"/", 302) http.Redirect(ctx.ResponseWriter, ctx.Request, ctx.Input.Request.URL.Path+"/", 302)
return return
} }
} else if strings.HasSuffix(requestPath, "/index.html") {
file := path.Join(staticDir, requestPath)
if utils.FileExists(file) {
oFile, err := os.Open(file)
if err != nil {
if RunMode == "dev" {
Warn("Can't open the file:", file, err)
}
http.NotFound(ctx.ResponseWriter, ctx.Request)
}
defer oFile.Close()
http.ServeContent(ctx.ResponseWriter, ctx.Request, file, finfo.ModTime(), oFile)
return
}
} }
//This block obtained from (https://github.com/smithfox/beego) - it should probably get merged into astaxie/beego after a pull request if strings.HasSuffix(requestPath, "/index.html") {
fileReader, err := os.Open(filePath)
if err != nil {
if RunMode == "dev" {
Warn("Can't open the file:", filePath, err)
}
http.NotFound(ctx.ResponseWriter, ctx.Request)
return
}
defer fileReader.Close()
http.ServeContent(ctx.ResponseWriter, ctx.Request, filePath, fileInfo.ModTime(), fileReader)
return
}
isStaticFileToCompress := false isStaticFileToCompress := false
if StaticExtensionsToGzip != nil && len(StaticExtensionsToGzip) > 0 {
for _, statExtension := range StaticExtensionsToGzip { for _, statExtension := range StaticExtensionsToGzip {
if strings.HasSuffix(strings.ToLower(file), strings.ToLower(statExtension)) { if strings.HasSuffix(strings.ToLower(filePath), strings.ToLower(statExtension)) {
isStaticFileToCompress = true isStaticFileToCompress = true
break break
} }
} }
if !isStaticFileToCompress {
http.ServeFile(ctx.ResponseWriter, ctx.Request, filePath)
return
} }
if isStaticFileToCompress { //to compress file
var contentEncoding string var contentEncoding string
if EnableGzip { if EnableGzip {
contentEncoding = getAcceptEncodingZip(ctx.Request) contentEncoding = getAcceptEncodingZip(ctx.Request)
} }
memzipfile, err := openMemZipFile(file, contentEncoding) memZipFile, err := openMemZipFile(filePath, contentEncoding)
if err != nil { if err != nil {
if RunMode == "dev" {
Warn("Can't compress the file:", filePath, err)
}
http.NotFound(ctx.ResponseWriter, ctx.Request)
return return
} }
@ -114,14 +128,10 @@ func serverStaticRouter(ctx *context.Context) {
} else if contentEncoding == "deflate" { } else if contentEncoding == "deflate" {
ctx.Output.Header("Content-Encoding", "deflate") ctx.Output.Header("Content-Encoding", "deflate")
} else { } else {
ctx.Output.Header("Content-Length", strconv.FormatInt(finfo.Size(), 10)) ctx.Output.Header("Content-Length", strconv.FormatInt(fileInfo.Size(), 10))
} }
http.ServeContent(ctx.ResponseWriter, ctx.Request, file, finfo.ModTime(), memzipfile) http.ServeContent(ctx.ResponseWriter, ctx.Request, filePath, fileInfo.ModTime(), memZipFile)
} else {
http.ServeFile(ctx.ResponseWriter, ctx.Request, file)
}
return return
} }
} }