github.com/weaveworks/common@v0.0.0-20230728070032-dd9e68f319d5/middleware/path_rewrite.go (about)

     1  package middleware
     2  
     3  import (
     4  	"net/http"
     5  	"net/url"
     6  	"regexp"
     7  
     8  	log "github.com/sirupsen/logrus"
     9  )
    10  
    11  // PathRewrite supports regex matching and replace on Request URIs
    12  func PathRewrite(regexp *regexp.Regexp, replacement string) Interface {
    13  	return pathRewrite{
    14  		regexp:      regexp,
    15  		replacement: replacement,
    16  	}
    17  }
    18  
    19  type pathRewrite struct {
    20  	regexp      *regexp.Regexp
    21  	replacement string
    22  }
    23  
    24  func (p pathRewrite) Wrap(next http.Handler) http.Handler {
    25  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    26  		r.RequestURI = p.regexp.ReplaceAllString(r.RequestURI, p.replacement)
    27  		r.URL.RawPath = p.regexp.ReplaceAllString(r.URL.EscapedPath(), p.replacement)
    28  		path, err := url.PathUnescape(r.URL.RawPath)
    29  		if err != nil {
    30  			log.Errorf("Got invalid url-encoded path %v after applying path rewrite %v: %v", r.URL.RawPath, p, err)
    31  			w.WriteHeader(http.StatusInternalServerError)
    32  			return
    33  		}
    34  		r.URL.Path = path
    35  		next.ServeHTTP(w, r)
    36  	})
    37  }
    38  
    39  // PathReplace replcase Request.RequestURI with the specified string.
    40  func PathReplace(replacement string) Interface {
    41  	return pathReplace(replacement)
    42  }
    43  
    44  type pathReplace string
    45  
    46  func (p pathReplace) Wrap(next http.Handler) http.Handler {
    47  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    48  		r.URL.Path = string(p)
    49  		r.RequestURI = string(p)
    50  		next.ServeHTTP(w, r)
    51  	})
    52  }