1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
|
// Copyright 2013 The Go Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd.
package httputil
import (
"bytes"
"crypto/sha1"
"errors"
"fmt"
"github.com/golang/gddo/httputil/header"
"io"
"io/ioutil"
"mime"
"net/http"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
// StaticServer serves static files.
type StaticServer struct {
// Dir specifies the location of the directory containing the files to serve.
Dir string
// MaxAge specifies the maximum age for the cache control and expiration
// headers.
MaxAge time.Duration
// Error specifies the function used to generate error responses. If Error
// is nil, then http.Error is used to generate error responses.
Error Error
// MIMETypes is a map from file extensions to MIME types.
MIMETypes map[string]string
mu sync.Mutex
etags map[string]string
}
func (ss *StaticServer) resolve(fname string) string {
if path.IsAbs(fname) {
panic("Absolute path not allowed when creating a StaticServer handler")
}
dir := ss.Dir
if dir == "" {
dir = "."
}
fname = filepath.FromSlash(fname)
return filepath.Join(dir, fname)
}
func (ss *StaticServer) mimeType(fname string) string {
ext := path.Ext(fname)
var mimeType string
if ss.MIMETypes != nil {
mimeType = ss.MIMETypes[ext]
}
if mimeType == "" {
mimeType = mime.TypeByExtension(ext)
}
if mimeType == "" {
mimeType = "application/octet-stream"
}
return mimeType
}
func (ss *StaticServer) openFile(fname string) (io.ReadCloser, int64, string, error) {
f, err := os.Open(fname)
if err != nil {
return nil, 0, "", err
}
fi, err := f.Stat()
if err != nil {
f.Close()
return nil, 0, "", err
}
const modeType = os.ModeDir | os.ModeSymlink | os.ModeNamedPipe | os.ModeSocket | os.ModeDevice
if fi.Mode()&modeType != 0 {
f.Close()
return nil, 0, "", errors.New("not a regular file")
}
return f, fi.Size(), ss.mimeType(fname), nil
}
// FileHandler returns a handler that serves a single file. The file is
// specified by a slash separated path relative to the static server's Dir
// field.
func (ss *StaticServer) FileHandler(fileName string) http.Handler {
id := fileName
fileName = ss.resolve(fileName)
return &staticHandler{
ss: ss,
id: func(_ string) string { return id },
open: func(_ string) (io.ReadCloser, int64, string, error) { return ss.openFile(fileName) },
}
}
// DirectoryHandler returns a handler that serves files from a directory tree.
// The directory is specified by a slash separated path relative to the static
// server's Dir field.
func (ss *StaticServer) DirectoryHandler(prefix, dirName string) http.Handler {
if !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
idBase := dirName
dirName = ss.resolve(dirName)
return &staticHandler{
ss: ss,
id: func(p string) string {
if !strings.HasPrefix(p, prefix) {
return "."
}
return path.Join(idBase, p[len(prefix):])
},
open: func(p string) (io.ReadCloser, int64, string, error) {
if !strings.HasPrefix(p, prefix) {
return nil, 0, "", errors.New("request url does not match directory prefix")
}
p = p[len(prefix):]
return ss.openFile(filepath.Join(dirName, filepath.FromSlash(p)))
},
}
}
// FilesHandler returns a handler that serves the concatentation of the
// specified files. The files are specified by slash separated paths relative
// to the static server's Dir field.
func (ss *StaticServer) FilesHandler(fileNames ...string) http.Handler {
// todo: cache concatenated files on disk and serve from there.
mimeType := ss.mimeType(fileNames[0])
var buf []byte
var openErr error
for _, fileName := range fileNames {
p, err := ioutil.ReadFile(ss.resolve(fileName))
if err != nil {
openErr = err
buf = nil
break
}
buf = append(buf, p...)
}
id := strings.Join(fileNames, " ")
return &staticHandler{
ss: ss,
id: func(_ string) string { return id },
open: func(p string) (io.ReadCloser, int64, string, error) {
return ioutil.NopCloser(bytes.NewReader(buf)), int64(len(buf)), mimeType, openErr
},
}
}
type staticHandler struct {
id func(fname string) string
open func(p string) (io.ReadCloser, int64, string, error)
ss *StaticServer
}
func (h *staticHandler) error(w http.ResponseWriter, r *http.Request, status int, err error) {
http.Error(w, http.StatusText(status), status)
}
func (h *staticHandler) etag(p string) (string, error) {
id := h.id(p)
h.ss.mu.Lock()
if h.ss.etags == nil {
h.ss.etags = make(map[string]string)
}
etag := h.ss.etags[id]
h.ss.mu.Unlock()
if etag != "" {
return etag, nil
}
// todo: if a concurrent goroutine is calculating the hash, then wait for
// it instead of computing it again here.
rc, _, _, err := h.open(p)
if err != nil {
return "", err
}
defer rc.Close()
w := sha1.New()
_, err = io.Copy(w, rc)
if err != nil {
return "", err
}
etag = fmt.Sprintf(`"%x"`, w.Sum(nil))
h.ss.mu.Lock()
h.ss.etags[id] = etag
h.ss.mu.Unlock()
return etag, nil
}
func (h *staticHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p := path.Clean(r.URL.Path)
if p != r.URL.Path {
http.Redirect(w, r, p, 301)
return
}
etag, err := h.etag(p)
if err != nil {
h.error(w, r, http.StatusNotFound, err)
return
}
maxAge := h.ss.MaxAge
if maxAge == 0 {
maxAge = 24 * time.Hour
}
if r.FormValue("v") != "" {
maxAge = 365 * 24 * time.Hour
}
cacheControl := fmt.Sprintf("public, max-age=%d", maxAge/time.Second)
for _, e := range header.ParseList(r.Header, "If-None-Match") {
if e == etag {
w.Header().Set("Cache-Control", cacheControl)
w.Header().Set("Etag", etag)
w.WriteHeader(http.StatusNotModified)
return
}
}
rc, cl, ct, err := h.open(p)
if err != nil {
h.error(w, r, http.StatusNotFound, err)
return
}
defer rc.Close()
w.Header().Set("Cache-Control", cacheControl)
w.Header().Set("Etag", etag)
if ct != "" {
w.Header().Set("Content-Type", ct)
}
if cl != 0 {
w.Header().Set("Content-Length", strconv.FormatInt(cl, 10))
}
w.WriteHeader(http.StatusOK)
if r.Method != "HEAD" {
io.Copy(w, rc)
}
}
|