Files
weave-scope/vendor/github.com/weaveworks/common/middleware/path_rewrite.go
Roland Schilter c817eccb9b Update github.com/weaveworks/common & deps
Bumped all packages that make the build fail:

    gvt update github.com/golang/protobuf/proto
    gvt fetch github.com/golang/protobuf/ptypes
    gvt fetch google.golang.org/genproto/googleapis/rpc/status
    gvt update google.golang.org/grpc/status
    gvt update google.golang.org/grpc/transport
    gvt update golang.org/x/net/http2
2017-06-21 12:19:17 +02:00

53 lines
1.3 KiB
Go

package middleware
import (
"net/http"
"net/url"
"regexp"
log "github.com/Sirupsen/logrus"
)
// 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)
r.URL.RawPath = p.regexp.ReplaceAllString(r.URL.EscapedPath(), p.replacement)
path, err := url.PathUnescape(r.URL.RawPath)
if err != nil {
log.Errorf("Got invalid url-encoded path %v after applying path rewrite %v: %v", r.URL.RawPath, p, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
r.URL.Path = path
next.ServeHTTP(w, r)
})
}
// PathReplace replcase Request.RequestURI with the specified string.
func PathReplace(replacement string) Interface {
return pathReplace(replacement)
}
type pathReplace string
func (p pathReplace) Wrap(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = string(p)
r.RequestURI = string(p)
next.ServeHTTP(w, r)
})
}