2016-02-26 15:29:53 +01:00
package middlewares
import (
"net/http"
"strings"
)
2017-05-28 05:50:03 +02:00
// ForwardedPrefixHeader is the default header to set prefix
const ForwardedPrefixHeader = "X-Forwarded-Prefix"
2017-04-16 19:24:26 +10:00
2016-02-26 15:29:53 +01:00
// StripPrefix is a middleware used to strip prefix from an URL request
type StripPrefix struct {
2016-04-06 13:06:31 +02:00
Handler http . Handler
Prefixes [ ] string
2016-02-26 15:29:53 +01:00
}
func ( s * StripPrefix ) ServeHTTP ( w http . ResponseWriter , r * http . Request ) {
2016-04-06 13:06:31 +02:00
for _ , prefix := range s . Prefixes {
2017-11-21 14:28:03 +01:00
if strings . HasPrefix ( r . URL . Path , prefix ) {
r . URL . Path = stripPrefix ( r . URL . Path , prefix )
if r . URL . RawPath != "" {
r . URL . RawPath = stripPrefix ( r . URL . RawPath , prefix )
}
2017-10-06 11:34:03 +02:00
s . serveRequest ( w , r , strings . TrimSpace ( prefix ) )
2016-04-06 14:30:29 +02:00
return
2016-04-06 13:06:31 +02:00
}
2016-02-26 15:29:53 +01:00
}
2016-04-06 13:06:31 +02:00
http . NotFound ( w , r )
2016-02-26 15:29:53 +01:00
}
2016-03-27 01:05:17 +01:00
2017-05-22 15:44:02 -07:00
func ( s * StripPrefix ) serveRequest ( w http . ResponseWriter , r * http . Request , prefix string ) {
2017-05-28 05:50:03 +02:00
r . Header . Add ( ForwardedPrefixHeader , prefix )
2017-05-22 15:44:02 -07:00
r . RequestURI = r . URL . RequestURI ( )
s . Handler . ServeHTTP ( w , r )
}
2016-03-27 01:05:17 +01:00
// SetHandler sets handler
func ( s * StripPrefix ) SetHandler ( Handler http . Handler ) {
s . Handler = Handler
}
2017-11-21 14:28:03 +01:00
func stripPrefix ( s , prefix string ) string {
return ensureLeadingSlash ( strings . TrimPrefix ( s , prefix ) )
}
func ensureLeadingSlash ( str string ) string {
return "/" + strings . TrimPrefix ( str , "/" )
}