Beego/staticfile.go

196 lines
5.1 KiB
Go
Raw Normal View History

2014-08-18 08:41:43 +00:00
// Copyright 2014 beego Author. All Rights Reserved.
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// http://www.apache.org/licenses/LICENSE-2.0
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2014-04-05 16:18:21 +00:00
package beego
import (
2015-11-11 08:22:40 +00:00
"bytes"
2014-04-05 16:18:21 +00:00
"net/http"
"os"
"path"
"path/filepath"
2014-04-05 16:18:21 +00:00
"strconv"
"strings"
2015-11-11 08:22:40 +00:00
"sync"
"errors"
"time"
2014-04-05 16:18:21 +00:00
"github.com/astaxie/beego/context"
)
2015-11-11 08:22:40 +00:00
var notStaticRequestErr = errors.New("request not a static file request")
2014-06-10 17:11:32 +00:00
func serverStaticRouter(ctx *context.Context) {
2014-08-04 07:31:27 +00:00
if ctx.Input.Method() != "GET" && ctx.Input.Method() != "HEAD" {
return
}
2015-09-22 04:19:31 +00:00
2015-11-11 08:22:40 +00:00
forbidden, filePath, fileInfo, err := lookupFile(ctx)
if err == notStaticRequestErr {
return
}
2015-09-22 04:19:31 +00:00
2015-11-11 08:22:40 +00:00
if forbidden {
exception("403", ctx)
return
}
2015-09-22 04:19:31 +00:00
2015-11-11 08:22:40 +00:00
if filePath == "" || fileInfo == nil {
if RunMode == "dev" {
Warn("Can't find/open the file:", filePath, err)
}
2015-09-22 04:19:31 +00:00
http.NotFound(ctx.ResponseWriter, ctx.Request)
return
}
2015-11-11 08:22:40 +00:00
if fileInfo.IsDir() {
//serveFile will list dir
http.ServeFile(ctx.ResponseWriter, ctx.Request, filePath)
return
}
2015-09-22 04:19:31 +00:00
2015-11-11 08:22:40 +00:00
var enableCompress = EnableGzip && isStaticCompress(filePath)
var acceptEncoding string
if enableCompress {
acceptEncoding = context.ParseEncoding(ctx.Request)
}
b, n, sch, err := openFile(filePath, fileInfo, acceptEncoding)
if err != nil {
if RunMode == "dev" {
Warn("Can't compress the file:", filePath, err)
2014-04-05 16:18:21 +00:00
}
2015-11-11 08:22:40 +00:00
http.NotFound(ctx.ResponseWriter, ctx.Request)
return
}
2015-09-22 04:19:31 +00:00
2015-11-11 08:22:40 +00:00
if b {
ctx.Output.Header("Content-Encoding", n)
} else {
ctx.Output.Header("Content-Length", strconv.FormatInt(sch.size, 10))
}
2014-04-05 16:18:21 +00:00
2015-11-11 08:22:40 +00:00
http.ServeContent(ctx.ResponseWriter, ctx.Request, filePath, sch.modTime, sch)
return
2014-04-05 16:18:21 +00:00
2015-11-11 08:22:40 +00:00
}
2014-04-05 16:18:21 +00:00
2015-11-11 08:22:40 +00:00
type serveContentHolder struct {
*strings.Reader
modTime time.Time
size int64
encoding string
}
2014-04-05 16:18:21 +00:00
2015-11-11 08:22:40 +00:00
var (
staticFileMap = make(map[string]*serveContentHolder)
mapLock sync.Mutex
)
func openFile(filePath string, fi os.FileInfo, acceptEncoding string) (bool, string, *serveContentHolder, error) {
mapKey := acceptEncoding + ":" + filePath
mapFile, ok := staticFileMap[mapKey]
if ok {
if mapFile.modTime == fi.ModTime() && mapFile.size == fi.Size() {
return mapFile.encoding != "", mapFile.encoding, mapFile, nil
}
}
mapLock.Lock()
delete(staticFileMap, mapKey)
defer mapLock.Unlock()
if mapFile, ok = staticFileMap[mapKey]; !ok {
file, err := os.Open(filePath)
if err != nil {
return false, "", nil, err
}
defer file.Close()
var bufferWriter bytes.Buffer
_, n, err := context.WriteFile(acceptEncoding, &bufferWriter, file)
if err != nil {
return false, "", nil, err
}
mapFile = &serveContentHolder{Reader: strings.NewReader(string(bufferWriter.Bytes())), modTime: fi.ModTime(), size: int64(bufferWriter.Len()), encoding: n}
staticFileMap[mapKey] = mapFile
}
return mapFile.encoding != "", mapFile.encoding, mapFile, nil
}
2015-11-12 02:48:36 +00:00
// isStaticCompress detect static files
2015-11-11 08:22:40 +00:00
func isStaticCompress(filePath string) bool {
for _, statExtension := range StaticExtensionsToGzip {
if strings.HasSuffix(strings.ToLower(filePath), strings.ToLower(statExtension)) {
return true
}
}
return false
}
2014-04-05 16:18:21 +00:00
2015-11-12 02:48:36 +00:00
// searchFile search the file by url path
// if none the static file prefix matches ,return notStaticRequestErr
2015-11-11 08:22:40 +00:00
func searchFile(ctx *context.Context) (string, os.FileInfo, error) {
requestPath := filepath.Clean(ctx.Input.Request.URL.Path)
// special processing : favicon.ico/robots.txt can be in any static dir
if requestPath == "/favicon.ico" || requestPath == "/robots.txt" {
file := path.Join(".", requestPath)
if fi, _ := os.Stat(file); fi != nil {
return file, fi, nil
}
for _, staticDir := range StaticDir {
filePath := path.Join(staticDir, requestPath)
if fi, _ := os.Stat(filePath); fi != nil {
return filePath, fi, nil
2014-04-05 16:18:21 +00:00
}
2015-11-11 08:22:40 +00:00
}
return "", nil, errors.New(requestPath + " file not find")
}
2015-09-22 04:19:31 +00:00
2015-11-11 08:22:40 +00:00
for prefix, staticDir := range StaticDir {
if len(prefix) == 0 {
continue
}
if !strings.Contains(requestPath, prefix) {
continue
2014-04-05 16:18:21 +00:00
}
2015-11-11 08:22:40 +00:00
if len(requestPath) > len(prefix) && requestPath[len(prefix)] != '/' {
continue
}
filePath := path.Join(staticDir, requestPath[len(prefix):])
if fi, err := os.Stat(filePath); fi != nil {
return filePath, fi, err
}
}
return "", nil, notStaticRequestErr
}
2015-11-12 02:48:36 +00:00
// lookupFile find the file to serve
// if the file is dir ,search the index.html as default file( MUST NOT A DIR also)
// if the index.html not exist or is a dir, give a forbidden response depending on DirectoryIndex
2015-11-11 08:22:40 +00:00
func lookupFile(ctx *context.Context) (bool, string, os.FileInfo, error) {
fp, fi, err := searchFile(ctx)
if fp == "" || fi == nil {
return false, "", nil, err
}
if !fi.IsDir() {
return false, fp, fi, err
}
ifp := filepath.Join(fp, "index.html")
if ifi, _ := os.Stat(ifp); ifi != nil && ifi.Mode().IsRegular() {
return false, ifp, ifi, err
2014-04-05 16:18:21 +00:00
}
2015-11-11 08:22:40 +00:00
return !DirectoryIndex, fp, fi, err
2014-04-05 16:18:21 +00:00
}