2016-12-02 12:40:18 +00:00
|
|
|
package middlewares
|
|
|
|
|
|
|
|
import (
|
2018-07-31 09:28:03 +00:00
|
|
|
"context"
|
2016-12-02 12:40:18 +00:00
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
// AddPrefix is a middleware used to add prefix to an URL request
|
|
|
|
type AddPrefix struct {
|
|
|
|
Handler http.Handler
|
|
|
|
Prefix string
|
|
|
|
}
|
|
|
|
|
2018-07-31 09:28:03 +00:00
|
|
|
type key string
|
|
|
|
|
|
|
|
const (
|
|
|
|
// AddPrefixKey is the key within the request context used to
|
|
|
|
// store the added prefix
|
|
|
|
AddPrefixKey key = "AddPrefix"
|
|
|
|
)
|
|
|
|
|
2016-12-02 12:40:18 +00:00
|
|
|
func (s *AddPrefix) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
r.URL.Path = s.Prefix + r.URL.Path
|
2017-12-15 02:50:07 +00:00
|
|
|
if r.URL.RawPath != "" {
|
|
|
|
r.URL.RawPath = s.Prefix + r.URL.RawPath
|
|
|
|
}
|
2016-12-02 12:40:18 +00:00
|
|
|
r.RequestURI = r.URL.RequestURI()
|
2018-07-31 09:28:03 +00:00
|
|
|
r = r.WithContext(context.WithValue(r.Context(), AddPrefixKey, s.Prefix))
|
2016-12-02 12:40:18 +00:00
|
|
|
s.Handler.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetHandler sets handler
|
|
|
|
func (s *AddPrefix) SetHandler(Handler http.Handler) {
|
|
|
|
s.Handler = Handler
|
|
|
|
}
|