req_params.go 728 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package http_api
  2. import (
  3. "errors"
  4. "io/ioutil"
  5. "net/http"
  6. "net/url"
  7. )
  8. type ReqParams struct {
  9. url.Values
  10. Body []byte
  11. }
  12. func NewReqParams(req *http.Request) (*ReqParams, error) {
  13. reqParams, err := url.ParseQuery(req.URL.RawQuery)
  14. if err != nil {
  15. return nil, err
  16. }
  17. data, err := ioutil.ReadAll(req.Body)
  18. if err != nil {
  19. return nil, err
  20. }
  21. return &ReqParams{reqParams, data}, nil
  22. }
  23. func (r *ReqParams) Get(key string) (string, error) {
  24. v, ok := r.Values[key]
  25. if !ok {
  26. return "", errors.New("key not in query params")
  27. }
  28. return v[0], nil
  29. }
  30. func (r *ReqParams) GetAll(key string) ([]string, error) {
  31. v, ok := r.Values[key]
  32. if !ok {
  33. return nil, errors.New("key not in query params")
  34. }
  35. return v, nil
  36. }