Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add generic path rewrite middleware #1381

Merged
merged 1 commit into from
Apr 27, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add generic path rewrite middleware
And fix a bug in the logging middleware.
  • Loading branch information
tomwilkie committed Apr 26, 2016
commit e81b1b98e9eb227c7358f0ee0258ec59ad3d84aa
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)
})
}