1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-25 21:11:29 +00:00
Beego/staticfile.go

235 lines
6.7 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"
2016-01-17 16:18:21 +00:00
"errors"
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"
"time"
2014-04-05 16:18:21 +00:00
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/logs"
"github.com/hashicorp/golang-lru"
2014-04-05 16:18:21 +00:00
)
2016-01-17 16:18:21 +00:00
var errNotStaticRequest = errors.New("request not a static file request")
2015-11-11 08:22:40 +00:00
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)
2016-01-17 16:18:21 +00:00
if err == errNotStaticRequest {
2015-11-11 08:22:40 +00:00
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 BConfig.RunMode == DEV {
logs.Warn("Can't find/open the file:", filePath, err)
2015-11-11 08:22:40 +00:00
}
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() {
requestURL := ctx.Input.URL()
if requestURL[len(requestURL)-1] != '/' {
2016-07-26 11:54:10 +00:00
redirectURL := requestURL + "/"
if ctx.Request.URL.RawQuery != "" {
redirectURL = redirectURL + "?" + ctx.Request.URL.RawQuery
}
ctx.Redirect(302, redirectURL)
} else {
//serveFile will list dir
http.ServeFile(ctx.ResponseWriter, ctx.Request, filePath)
}
2015-11-11 08:22:40 +00:00
return
2020-06-16 06:56:58 +00:00
} else if fileInfo.Size() > int64(BConfig.WebConfig.StaticCacheFileSize) {
//over size file serve with http module
http.ServeFile(ctx.ResponseWriter, ctx.Request, filePath)
return
2015-11-11 08:22:40 +00:00
}
2015-09-22 04:19:31 +00:00
2015-12-09 15:35:04 +00:00
var enableCompress = BConfig.EnableGzip && isStaticCompress(filePath)
2015-11-11 08:22:40 +00:00
var acceptEncoding string
if enableCompress {
acceptEncoding = context.ParseEncoding(ctx.Request)
}
2018-05-07 07:27:13 +00:00
b, n, sch, reader, err := openFile(filePath, fileInfo, acceptEncoding)
2015-11-11 08:22:40 +00:00
if err != nil {
if BConfig.RunMode == DEV {
logs.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
2018-05-07 07:27:13 +00:00
http.ServeContent(ctx.ResponseWriter, ctx.Request, filePath, sch.modTime, reader)
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 {
data []byte
modTime time.Time
size int64
originSize int64 //original file size:to judge file changed
encoding string
2015-11-11 08:22:40 +00:00
}
2014-04-05 16:18:21 +00:00
2018-05-07 07:27:13 +00:00
type serveContentReader struct {
*bytes.Reader
}
2015-11-11 08:22:40 +00:00
var (
staticFileLruCache *lru.Cache
lruLock sync.RWMutex
2015-11-11 08:22:40 +00:00
)
2018-05-07 07:27:13 +00:00
func openFile(filePath string, fi os.FileInfo, acceptEncoding string) (bool, string, *serveContentHolder, *serveContentReader, error) {
if staticFileLruCache == nil {
2020-06-02 12:02:58 +00:00
//avoid lru cache error
if BConfig.WebConfig.StaticCacheFileNum >= 1 {
staticFileLruCache, _ = lru.New(BConfig.WebConfig.StaticCacheFileNum)
} else {
staticFileLruCache, _ = lru.New(1)
}
}
2015-11-11 08:22:40 +00:00
mapKey := acceptEncoding + ":" + filePath
lruLock.RLock()
var mapFile *serveContentHolder
if cacheItem, ok := staticFileLruCache.Get(mapKey); ok {
mapFile = cacheItem.(*serveContentHolder)
}
lruLock.RUnlock()
if isOk(mapFile, fi) {
2018-05-07 07:27:13 +00:00
reader := &serveContentReader{Reader: bytes.NewReader(mapFile.data)}
return mapFile.encoding != "", mapFile.encoding, mapFile, reader, nil
2015-11-11 08:22:40 +00:00
}
lruLock.Lock()
defer lruLock.Unlock()
if cacheItem, ok := staticFileLruCache.Get(mapKey); ok {
mapFile = cacheItem.(*serveContentHolder)
}
if !isOk(mapFile, fi) {
2015-11-11 08:22:40 +00:00
file, err := os.Open(filePath)
if err != nil {
2018-05-07 07:27:13 +00:00
return false, "", nil, nil, err
2015-11-11 08:22:40 +00:00
}
defer file.Close()
var bufferWriter bytes.Buffer
_, n, err := context.WriteFile(acceptEncoding, &bufferWriter, file)
if err != nil {
2018-05-07 07:27:13 +00:00
return false, "", nil, nil, err
2015-11-11 08:22:40 +00:00
}
mapFile = &serveContentHolder{data: bufferWriter.Bytes(), modTime: fi.ModTime(), size: int64(bufferWriter.Len()), originSize: fi.Size(), encoding: n}
if isOk(mapFile, fi) {
staticFileLruCache.Add(mapKey, mapFile)
}
2015-11-11 08:22:40 +00:00
}
2018-05-07 07:27:13 +00:00
reader := &serveContentReader{Reader: bytes.NewReader(mapFile.data)}
return mapFile.encoding != "", mapFile.encoding, mapFile, reader, nil
2015-11-11 08:22:40 +00:00
}
func isOk(s *serveContentHolder, fi os.FileInfo) bool {
if s == nil {
return false
} else if s.size > int64(BConfig.WebConfig.StaticCacheFileSize) {
return false
}
return s.modTime == fi.ModTime() && s.originSize == fi.Size()
}
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 {
2015-12-09 15:35:04 +00:00
for _, statExtension := range BConfig.WebConfig.StaticExtensionsToGzip {
2015-11-11 08:22:40 +00:00
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) {
2015-12-10 13:59:54 +00:00
requestPath := filepath.ToSlash(filepath.Clean(ctx.Request.URL.Path))
2015-11-11 08:22:40 +00:00
// 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
}
2015-12-09 15:35:04 +00:00
for _, staticDir := range BConfig.WebConfig.StaticDir {
2015-11-11 08:22:40 +00:00
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, errNotStaticRequest
2015-11-11 08:22:40 +00:00
}
2015-09-22 04:19:31 +00:00
2015-12-09 15:35:04 +00:00
for prefix, staticDir := range BConfig.WebConfig.StaticDir {
2015-11-11 08:22:40 +00:00
if !strings.Contains(requestPath, prefix) {
continue
2014-04-05 16:18:21 +00:00
}
2018-10-01 07:16:35 +00:00
if prefix != "/" && len(requestPath) > len(prefix) && requestPath[len(prefix)] != '/' {
2015-11-11 08:22:40 +00:00
continue
}
filePath := path.Join(staticDir, requestPath[len(prefix):])
if fi, err := os.Stat(filePath); fi != nil {
return filePath, fi, err
}
}
2016-01-17 16:18:21 +00:00
return "", nil, errNotStaticRequest
2015-11-11 08:22:40 +00:00
}
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
}
2016-09-11 13:27:27 +00:00
if requestURL := ctx.Input.URL(); requestURL[len(requestURL)-1] == '/' {
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-12-09 15:35:04 +00:00
return !BConfig.WebConfig.DirectoryIndex, fp, fi, err
2014-04-05 16:18:21 +00:00
}