2017-12-16 01:19:37 +00:00
|
|
|
package cleanhttp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"unicode"
|
|
|
|
)
|
|
|
|
|
|
|
|
// HandlerInput provides input options to cleanhttp's handlers
|
|
|
|
type HandlerInput struct {
|
|
|
|
ErrStatus int
|
|
|
|
}
|
|
|
|
|
|
|
|
// PrintablePathCheckHandler is a middleware that ensures the request path
|
|
|
|
// contains only printable runes.
|
|
|
|
func PrintablePathCheckHandler(next http.Handler, input *HandlerInput) http.Handler {
|
2017-12-18 14:40:22 +00:00
|
|
|
if input == nil {
|
|
|
|
input = &HandlerInput{
|
|
|
|
ErrStatus: http.StatusBadRequest,
|
2017-12-16 01:19:37 +00:00
|
|
|
}
|
2017-12-18 14:40:22 +00:00
|
|
|
}
|
2017-12-16 01:19:37 +00:00
|
|
|
|
2017-12-18 14:40:22 +00:00
|
|
|
// Default to http.StatusBadRequest on error
|
|
|
|
if input.ErrStatus == 0 {
|
|
|
|
input.ErrStatus = http.StatusBadRequest
|
|
|
|
}
|
2017-12-16 01:19:37 +00:00
|
|
|
|
2017-12-18 14:40:22 +00:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
// Nil-check on input to make it optional
|
2017-12-16 01:19:37 +00:00
|
|
|
// Check URL path for non-printable characters
|
|
|
|
idx := strings.IndexFunc(r.URL.Path, func(c rune) bool {
|
|
|
|
return !unicode.IsPrint(c)
|
|
|
|
})
|
|
|
|
|
|
|
|
if idx != -1 {
|
|
|
|
w.WriteHeader(input.ErrStatus)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
})
|
|
|
|
}
|