2015-01-30 01:52:18 -05:00
|
|
|
// Package extensionless is middleware for clean URLs. A root path is
|
2015-01-30 00:02:58 -05:00
|
|
|
// passed in as well as possible extensions to add, internally,
|
|
|
|
// to paths requested. The first path+ext that matches a resource
|
|
|
|
// that exists will be used.
|
|
|
|
package extensionless
|
2015-01-13 14:43:45 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"strings"
|
2015-01-30 00:02:58 -05:00
|
|
|
|
|
|
|
"github.com/mholt/caddy/middleware"
|
2015-01-13 14:43:45 -05:00
|
|
|
)
|
|
|
|
|
2015-01-30 00:02:58 -05:00
|
|
|
// New creates a new instance of middleware that assumes extensions
|
|
|
|
// so the site can use cleaner, extensionless URLs
|
|
|
|
func New(c middleware.Controller) (middleware.Middleware, error) {
|
2015-01-19 01:11:21 -05:00
|
|
|
var extensions []string
|
2015-01-30 00:02:58 -05:00
|
|
|
var root = c.Root() // TODO: Big gotcha! Save this now before it goes away! We can't get this later during a request!
|
2015-01-19 01:11:21 -05:00
|
|
|
|
2015-01-30 00:02:58 -05:00
|
|
|
for c.Next() {
|
|
|
|
if !c.NextArg() {
|
|
|
|
return nil, c.ArgErr()
|
2015-01-19 01:11:21 -05:00
|
|
|
}
|
2015-01-30 00:02:58 -05:00
|
|
|
extensions = append(extensions, c.Val())
|
|
|
|
for c.NextArg() {
|
|
|
|
extensions = append(extensions, c.Val())
|
2015-01-19 01:11:21 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-13 14:43:45 -05:00
|
|
|
resourceExists := func(path string) bool {
|
|
|
|
_, err := os.Stat(root + path)
|
|
|
|
// technically we should use os.IsNotExist(err)
|
2015-01-19 01:11:21 -05:00
|
|
|
// but we don't handle any other kinds of errors anyway
|
2015-01-13 14:43:45 -05:00
|
|
|
return err == nil
|
|
|
|
}
|
|
|
|
|
|
|
|
hasExt := func(r *http.Request) bool {
|
|
|
|
if r.URL.Path[len(r.URL.Path)-1] == '/' {
|
|
|
|
// directory
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
lastSep := strings.LastIndex(r.URL.Path, "/")
|
|
|
|
lastDot := strings.LastIndex(r.URL.Path, ".")
|
|
|
|
return lastDot > lastSep
|
|
|
|
}
|
|
|
|
|
|
|
|
return func(next http.HandlerFunc) http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if !hasExt(r) {
|
|
|
|
for _, ext := range extensions {
|
|
|
|
if resourceExists(r.URL.Path + ext) {
|
|
|
|
r.URL.Path = r.URL.Path + ext
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
next(w, r)
|
|
|
|
}
|
2015-01-30 00:02:58 -05:00
|
|
|
}, nil
|
2015-01-13 14:43:45 -05:00
|
|
|
}
|