go-zero/rest/httpx/util.go

39 lines
750 B
Go
Raw Normal View History

2020-08-12 12:25:52 +08:00
package httpx
2020-07-29 18:00:04 +08:00
import "net/http"
const xForwardedFor = "X-Forwarded-For"
2020-07-29 18:00:04 +08:00
// GetFormValues returns the form values.
func GetFormValues(r *http.Request) (map[string]any, error) {
if err := r.ParseForm(); err != nil {
return nil, err
}
if err := r.ParseMultipartForm(maxMemory); err != nil {
if err != http.ErrNotMultipart {
return nil, err
}
}
params := make(map[string]any, len(r.Form))
for name := range r.Form {
formValue := r.Form.Get(name)
if len(formValue) > 0 {
params[name] = formValue
}
}
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 {
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
}