Add generic path rewrite middleware

And fix a bug in the logging middleware.
This commit is contained in:
Tom Wilkie
2016-04-26 14:26:13 +01:00
parent 3bfb8c4c85
commit e81b1b98e9
2 changed files with 28 additions and 1 deletions

View File

@@ -14,9 +14,10 @@ import (
var Logging = Func(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
begin := time.Now()
uri := r.RequestURI // capture the URI before running next, as it may get rewritten
i := &interceptor{ResponseWriter: w, statusCode: http.StatusOK}
next.ServeHTTP(i, r)
log.Infof("%s %s (%d) %s", r.Method, r.RequestURI, i.statusCode, time.Since(begin))
log.Infof("%s %s (%d) %s", r.Method, uri, i.statusCode, time.Since(begin))
})
})

View File

@@ -0,0 +1,26 @@
package middleware
import (
"net/http"
"regexp"
)
// PathRewrite supports regex matching and replace on Request URIs
func PathRewrite(regexp *regexp.Regexp, replacement string) Interface {
return pathRewrite{
regexp: regexp,
replacement: replacement,
}
}
type pathRewrite struct {
regexp *regexp.Regexp
replacement string
}
func (p pathRewrite) Wrap(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.RequestURI = p.regexp.ReplaceAllString(r.RequestURI, p.replacement)
next.ServeHTTP(w, r)
})
}