Skip to content

Commit

Permalink
Merge pull request #1381 from weaveworks/middleware
Browse files Browse the repository at this point in the history
Add generic path rewrite middleware
  • Loading branch information
paulbellamy committed Apr 27, 2016
2 parents 455b599 + e81b1b9 commit 0f3b6bc
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
3 changes: 2 additions & 1 deletion common/middleware/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})
})

Expand Down
26 changes: 26 additions & 0 deletions common/middleware/path_rewrite.go
Original file line number Diff line number Diff line change
@@ -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)
})
}

0 comments on commit 0f3b6bc

Please sign in to comment.