2020-08-12 12:25:52 +08:00
|
|
|
package httpx
|
2020-07-29 18:00:04 +08:00
|
|
|
|
2024-03-09 13:48:11 +08:00
|
|
|
import (
|
|
|
|
|
"errors"
|
2024-12-23 00:56:20 +08:00
|
|
|
"fmt"
|
2024-03-09 13:48:11 +08:00
|
|
|
"net/http"
|
2024-12-23 00:56:20 +08:00
|
|
|
"strings"
|
2024-03-09 13:48:11 +08:00
|
|
|
)
|
2020-07-29 18:00:04 +08:00
|
|
|
|
2024-12-23 00:56:20 +08:00
|
|
|
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
|
|
|
|
|
)
|
2020-07-29 18:00:04 +08:00
|
|
|
|
2024-12-23 00:56:20 +08:00
|
|
|
// 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
|
2023-01-24 16:32:02 +08:00
|
|
|
func GetFormValues(r *http.Request) (map[string]any, error) {
|
2022-07-16 23:40:53 +08:00
|
|
|
if err := r.ParseForm(); err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := r.ParseMultipartForm(maxMemory); err != nil {
|
2024-03-09 13:48:11 +08:00
|
|
|
if !errors.Is(err, http.ErrNotMultipart) {
|
2022-07-16 23:40:53 +08:00
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-12-23 00:56:20 +08:00
|
|
|
var n int
|
2023-01-24 16:32:02 +08:00
|
|
|
params := make(map[string]any, len(r.Form))
|
2024-11-02 21:55:37 +08:00
|
|
|
for name, values := range r.Form {
|
|
|
|
|
filtered := make([]string, 0, len(values))
|
|
|
|
|
for _, v := range values {
|
2024-12-23 00:56:20 +08:00
|
|
|
if n < maxFormParamCount {
|
2024-11-02 21:55:37 +08:00
|
|
|
filtered = append(filtered, v)
|
2024-12-23 00:56:20 +08:00
|
|
|
n++
|
|
|
|
|
} else {
|
|
|
|
|
return nil, fmt.Errorf("too many form values, error: %s", r.Form.Encode())
|
2024-11-02 21:55:37 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if len(filtered) > 0 {
|
2024-12-23 00:56:20 +08:00
|
|
|
if strings.HasSuffix(name, arraySuffix) {
|
|
|
|
|
name = name[:len(name)-2]
|
|
|
|
|
}
|
2024-11-02 21:55:37 +08:00
|
|
|
params[name] = filtered
|
2022-07-16 23:40:53 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return params, nil
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-09 13:50:21 +08:00
|
|
|
// GetRemoteAddr returns the peer address, supports X-Forward-For.
|
2020-07-29 18:00:04 +08:00
|
|
|
func GetRemoteAddr(r *http.Request) string {
|
2021-02-26 16:27:04 +08:00
|
|
|
v := r.Header.Get(xForwardedFor)
|
2020-07-29 18:00:04 +08:00
|
|
|
if len(v) > 0 {
|
|
|
|
|
return v
|
|
|
|
|
}
|
2021-10-20 17:50:01 +08:00
|
|
|
|
2020-07-29 18:00:04 +08:00
|
|
|
return r.RemoteAddr
|
|
|
|
|
}
|