Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 46 lines (38 sloc) 1.052 kb
b105d32 @paulbellamy Adding Static middleware for serving static files
authored
1 package mango
2
3 import (
4 "io/ioutil"
5 "os"
d968516 @paulbellamy Running go fmt
authored
6 "path"
b105d32 @paulbellamy Adding Static middleware for serving static files
authored
7 )
8
6d064af @paulbellamy Updating to compile on weekly.2012-03-04
authored
9 func fileIsRegular(fi os.FileInfo) bool {
d968516 @paulbellamy Running go fmt
authored
10 return fi.Mode()&(os.ModeDir|os.ModeSymlink|os.ModeNamedPipe|os.ModeSocket|os.ModeDevice) == 0
6d064af @paulbellamy Updating to compile on weekly.2012-03-04
authored
11 }
12
b105d32 @paulbellamy Adding Static middleware for serving static files
authored
13 func fileExists(filename string) bool {
14 info, err := os.Stat(filename)
15 if err != nil {
16 return false
6d064af @paulbellamy Updating to compile on weekly.2012-03-04
authored
17 } else if !fileIsRegular(info) {
d968516 @paulbellamy Running go fmt
authored
18 return false
19 }
b105d32 @paulbellamy Adding Static middleware for serving static files
authored
20
21 return true
22 }
23
6d064af @paulbellamy Updating to compile on weekly.2012-03-04
authored
24 func readFile(filename string) (string, error) {
b105d32 @paulbellamy Adding Static middleware for serving static files
authored
25 body, err := ioutil.ReadFile(filename)
26 return string(body), err
27 }
28
29 func Static(directory string) Middleware {
30 return func(env Env, app App) (Status, Headers, Body) {
31 // See if we can serve a file
32 file := path.Join(directory, env.Request().URL.Path)
33 if fileExists(file) && (env.Request().Method == "GET" || env.Request().Method == "HEAD") {
34 if body, err := readFile(file); err == nil {
3dd9abe @paulbellamy Adding mime-type handling to mango.Static, and mango.MimeType(extensi…
authored
35 mime_type := []string{MimeType(path.Ext(file), "application/octet-stream")}
36 return 200, Headers{"Content-Type": mime_type}, Body(body)
b105d32 @paulbellamy Adding Static middleware for serving static files
authored
37 } else {
38 panic(err)
39 }
40 }
41
42 // No file found, pass on to app
43 return app(env)
44 }
45 }
Something went wrong with that request. Please try again.