github.com/msales/pkg/v3@v3.24.0/httpx/middleware/query_normalizer.go (about)

     1  package middleware
     2  
     3  import (
     4  	"net/http"
     5  	"net/url"
     6  	"strconv"
     7  	"strings"
     8  )
     9  
    10  const encodedBracket = "%5B"
    11  
    12  // WithQueryNormalizer fixes wrong php query string handling as array
    13  func WithQueryNormalizer(h http.Handler) http.Handler {
    14  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    15  		if -1 == strings.Index(r.URL.RawQuery, "[") && -1 == strings.Index(r.URL.RawQuery, encodedBracket) {
    16  			h.ServeHTTP(w, r)
    17  
    18  			return
    19  		}
    20  
    21  		qs := r.URL.Query()
    22  		normalizedQuery := make(url.Values, len(qs))
    23  
    24  		for key, vals := range qs {
    25  			newKey := normalizedQueryKey(key)
    26  
    27  			for _, v := range vals {
    28  				normalizedQuery.Add(newKey, v)
    29  			}
    30  		}
    31  
    32  		r.URL.RawQuery = normalizedQuery.Encode()
    33  
    34  		h.ServeHTTP(w, r)
    35  	})
    36  }
    37  
    38  func normalizedQueryKey(key string) string {
    39  	strs := strings.Split(key, "[")
    40  	if len(strs) == 1 {
    41  		return key
    42  	}
    43  
    44  	for i, str := range strs {
    45  		if _, err := strconv.Atoi(str[:len(str)-1]); err == nil {
    46  			strs[i] = "]"
    47  		}
    48  	}
    49  	return strings.Join(strs, "[")
    50  }