feat: support form array in three notations (#4498)

Signed-off-by: kevin <wanjunfeng@gmail.com>
This commit is contained in:
Kevin Wan
2024-12-23 00:56:20 +08:00
committed by GitHub
parent 2159d112c3
commit 1d9159ea39
6 changed files with 452 additions and 81 deletions

View File

@@ -2,12 +2,23 @@ package httpx
import (
"errors"
"fmt"
"net/http"
"strings"
)
const xForwardedFor = "X-Forwarded-For"
const (
xForwardedFor = "X-Forwarded-For"
arraySuffix = "[]"
// most servers and clients have a limit of 8192 bytes (8 KB)
// one parameter at least take 4 chars, for example `?a=b&c=d`
maxFormParamCount = 2048
)
// GetFormValues returns the form values.
// GetFormValues returns the form values supporting three array notation formats:
// 1. Standard notation: /api?names=alice&names=bob
// 2. Comma notation: /api?names=alice,bob
// 3. Bracket notation: /api?names[]=alice&names[]=bob
func GetFormValues(r *http.Request) (map[string]any, error) {
if err := r.ParseForm(); err != nil {
return nil, err
@@ -19,16 +30,23 @@ func GetFormValues(r *http.Request) (map[string]any, error) {
}
}
var n int
params := make(map[string]any, len(r.Form))
for name, values := range r.Form {
filtered := make([]string, 0, len(values))
for _, v := range values {
if len(v) > 0 {
if n < maxFormParamCount {
filtered = append(filtered, v)
n++
} else {
return nil, fmt.Errorf("too many form values, error: %s", r.Form.Encode())
}
}
if len(filtered) > 0 {
if strings.HasSuffix(name, arraySuffix) {
name = name[:len(name)-2]
}
params[name] = filtered
}
}