github.com/orangenpresse/up@v0.6.0/http/static/static.go (about) 1 // Package static provides static file serving with HTTP cache support. 2 package static 3 4 import ( 5 "net/http" 6 "os" 7 "path/filepath" 8 "strings" 9 10 "github.com/apex/up" 11 ) 12 13 // New static handler. 14 func New(c *up.Config) http.Handler { 15 return http.FileServer(http.Dir(c.Static.Dir)) 16 } 17 18 // NewDynamic static handler for dynamic apps. 19 func NewDynamic(c *up.Config, next http.Handler) http.Handler { 20 prefix := normalizePrefix(c.Static.Prefix) 21 dir := c.Static.Dir 22 23 if dir == "" { 24 return next 25 } 26 27 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 28 var skip bool 29 path := r.URL.Path 30 31 // prefix 32 if prefix != "" { 33 if strings.HasPrefix(path, prefix) { 34 path = strings.Replace(path, prefix, "/", 1) 35 } else { 36 skip = true 37 } 38 } 39 40 // convert 41 path = filepath.FromSlash(path) 42 43 // file exists, serve it 44 if !skip { 45 file := filepath.Join(dir, path) 46 info, err := os.Stat(file) 47 if !os.IsNotExist(err) && !info.IsDir() { 48 http.ServeFile(w, r, file) 49 return 50 } 51 } 52 53 // delegate 54 next.ServeHTTP(w, r) 55 }) 56 } 57 58 // normalizePrefix returns a prefix path normalized with leading and trailing "/". 59 func normalizePrefix(s string) string { 60 if !strings.HasPrefix(s, "/") { 61 s = "/" + s 62 } 63 64 if !strings.HasSuffix(s, "/") { 65 s = s + "/" 66 } 67 68 return s 69 }