Skip to content

Instantly share code, notes, and snippets.

@rday
Created November 15, 2014 18:22
Show Gist options
  • Save rday/a8d457ced018e5970e19 to your computer and use it in GitHub Desktop.
Save rday/a8d457ced018e5970e19 to your computer and use it in GitHub Desktop.
Embedded Static Handler for Martini
package main
import (
"bytes"
"github.com/go-martini/martini"
"log"
"net/http"
"path"
"time"
"strings"
)
type ReadAssetFn func(string) ([]byte, error)
func prepareStaticOptions(options []martini.StaticOptions) martini.StaticOptions {
var opt martini.StaticOptions
if len(options) > 0 {
opt = options[0]
}
// Defaults
if len(opt.IndexFile) == 0 {
opt.IndexFile = "index.html"
}
// Normalize the prefix if provided
if opt.Prefix != "" {
// Ensure we have a leading '/'
if opt.Prefix[0] != '/' {
opt.Prefix = "/" + opt.Prefix
}
// Remove any trailing '/'
opt.Prefix = strings.TrimRight(opt.Prefix, "/")
}
return opt
}
// EmbeddedStatic returns a middleware handler that serves static files in the given directory.
func EmbeddedStatic(fn ReadAssetFn, staticOpt ...martini.StaticOptions) martini.Handler {
opt := prepareStaticOptions(staticOpt)
lastMod := time.Now().Local()
return func(res http.ResponseWriter, req *http.Request, log *log.Logger) {
if req.Method != "GET" && req.Method != "HEAD" {
return
}
if opt.Exclude != "" && strings.HasPrefix(req.URL.Path, opt.Exclude) {
return
}
file := req.URL.Path[1:]
// if we have a prefix, filter requests by stripping the prefix
if opt.Prefix != "" {
if !strings.HasPrefix(file, opt.Prefix) {
return
}
file = file[len(opt.Prefix):]
if file != "" && file[0] != '/' {
return
}
}
f, err := fn(file)
if err != nil {
if strings.HasSuffix(req.URL.Path, "/") {
file = path.Join(file, opt.IndexFile)
f, err = fn(file)
if err != nil {
return
}
} else {
// try any fallback before giving up
if opt.Fallback != "" {
file = opt.Fallback // so that logging stays true
f, err = fn(opt.Fallback)
if err != nil {
return
}
} else {
return
}
}
}
if !opt.SkipLogging {
log.Println("[Static] Serving " + file)
}
// Add an Expires header to the static content
if opt.Expires != nil {
res.Header().Set("Expires", opt.Expires())
}
content := bytes.NewReader(f)
http.ServeContent(res, req, file, lastMod, content)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment