1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // HTTP file system request handler
23 // A Dir implements http.FileSystem using the native file
24 // system restricted to a specific directory tree.
27 func (d Dir) Open(name string) (File, error) {
28 if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 {
29 return nil, errors.New("http: invalid character in file path")
31 f, err := os.Open(filepath.Join(string(d), filepath.FromSlash(path.Clean("/"+name))))
38 // A FileSystem implements access to a collection of named files.
39 // The elements in a file path are separated by slash ('/', U+002F)
40 // characters, regardless of host operating system convention.
41 type FileSystem interface {
42 Open(name string) (File, error)
45 // A File is returned by a FileSystem's Open method and can be
46 // served by the FileServer implementation.
49 Stat() (*os.FileInfo, error)
50 Readdir(count int) ([]os.FileInfo, error)
51 Read([]byte) (int, error)
52 Seek(offset int64, whence int) (int64, error)
55 // Heuristic: b is text if it is valid UTF-8 and doesn't
56 // contain any unprintable ASCII or Unicode characters.
57 func isText(b []byte) bool {
58 for len(b) > 0 && utf8.FullRune(b) {
59 rune, size := utf8.DecodeRune(b)
60 if size == 1 && rune == utf8.RuneError {
64 if 0x7F <= rune && rune <= 0x9F {
69 case '\n', '\r', '\t':
81 func dirList(w ResponseWriter, f File) {
82 w.Header().Set("Content-Type", "text/html; charset=utf-8")
83 fmt.Fprintf(w, "<pre>\n")
85 dirs, err := f.Readdir(100)
86 if err != nil || len(dirs) == 0 {
89 for _, d := range dirs {
95 fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", name, name)
98 fmt.Fprintf(w, "</pre>\n")
101 // name is '/'-separated, not filepath.Separator.
102 func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
103 const indexPage = "/index.html"
105 // redirect .../index.html to .../
106 // can't use Redirect() because that would make the path absolute,
107 // which would be a problem running under StripPrefix
108 if strings.HasSuffix(r.URL.Path, indexPage) {
109 localRedirect(w, r, "./")
113 f, err := fs.Open(name)
115 // TODO expose actual error?
123 // TODO expose actual error?
129 // redirect to canonical path: / at end of directory url
130 // r.URL.Path always begins with /
133 if url[len(url)-1] != '/' {
134 localRedirect(w, r, path.Base(url)+"/")
138 if url[len(url)-1] == '/' {
139 localRedirect(w, r, "../"+path.Base(url))
145 if t, _ := time.Parse(TimeFormat, r.Header.Get("If-Modified-Since")); t != nil && d.Mtime_ns/1e9 <= t.Seconds() {
146 w.WriteHeader(StatusNotModified)
149 w.Header().Set("Last-Modified", time.SecondsToUTC(d.Mtime_ns/1e9).Format(TimeFormat))
151 // use contents of index.html for directory, if present
153 index := name + indexPage
154 ff, err := fs.Open(index)
175 // If Content-Type isn't set, use the file's extension to find it.
176 if w.Header().Get("Content-Type") == "" {
177 ctype := mime.TypeByExtension(filepath.Ext(name))
179 // read a chunk to decide between utf-8 text and binary
181 n, _ := io.ReadFull(f, buf[:])
184 ctype = "text/plain; charset=utf-8"
187 ctype = "application/octet-stream"
189 f.Seek(0, os.SEEK_SET) // rewind to output whole file
191 w.Header().Set("Content-Type", ctype)
194 // handle Content-Range header.
195 // TODO(adg): handle multiple ranges
196 ranges, err := parseRange(r.Header.Get("Range"), size)
197 if err == nil && len(ranges) > 1 {
198 err = errors.New("multiple ranges not supported")
201 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
204 if len(ranges) == 1 {
206 if _, err := f.Seek(ra.start, os.SEEK_SET); err != nil {
207 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
211 code = StatusPartialContent
212 w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", ra.start, ra.start+ra.length-1, d.Size))
215 w.Header().Set("Accept-Ranges", "bytes")
216 if w.Header().Get("Content-Encoding") == "" {
217 w.Header().Set("Content-Length", strconv.Itoa64(size))
222 if r.Method != "HEAD" {
227 // localRedirect gives a Moved Permanently response.
228 // It does not convert relative paths to absolute paths like Redirect does.
229 func localRedirect(w ResponseWriter, r *Request, newPath string) {
230 if q := r.URL.RawQuery; q != "" {
233 w.Header().Set("Location", newPath)
234 w.WriteHeader(StatusMovedPermanently)
237 // ServeFile replies to the request with the contents of the named file or directory.
238 func ServeFile(w ResponseWriter, r *Request, name string) {
239 dir, file := filepath.Split(name)
240 serveFile(w, r, Dir(dir), file, false)
243 type fileHandler struct {
247 // FileServer returns a handler that serves HTTP requests
248 // with the contents of the file system rooted at root.
250 // To use the operating system's file system implementation,
253 // http.Handle("/", http.FileServer(http.Dir("/tmp")))
254 func FileServer(root FileSystem) Handler {
255 return &fileHandler{root}
258 func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
260 if !strings.HasPrefix(upath, "/") {
264 serveFile(w, r, f.root, path.Clean(upath), true)
267 // httpRange specifies the byte range to be sent to the client.
268 type httpRange struct {
272 // parseRange parses a Range header string as per RFC 2616.
273 func parseRange(s string, size int64) ([]httpRange, error) {
275 return nil, nil // header not present
278 if !strings.HasPrefix(s, b) {
279 return nil, errors.New("invalid range")
281 var ranges []httpRange
282 for _, ra := range strings.Split(s[len(b):], ",") {
283 i := strings.Index(ra, "-")
285 return nil, errors.New("invalid range")
287 start, end := ra[:i], ra[i+1:]
290 // If no start is specified, end specifies the
291 // range start relative to the end of the file.
292 i, err := strconv.Atoi64(end)
294 return nil, errors.New("invalid range")
300 r.length = size - r.start
302 i, err := strconv.Atoi64(start)
303 if err != nil || i > size || i < 0 {
304 return nil, errors.New("invalid range")
308 // If no end is specified, range extends to end of the file.
309 r.length = size - r.start
311 i, err := strconv.Atoi64(end)
312 if err != nil || r.start > i {
313 return nil, errors.New("invalid range")
318 r.length = i - r.start + 1
321 ranges = append(ranges, r)