url_param.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package requestutils
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strconv"
  6. "github.com/go-chi/chi"
  7. "github.com/porter-dev/porter/api/server/shared/apierrors"
  8. "github.com/porter-dev/porter/api/types"
  9. )
  10. const (
  11. urlParamNotFoundFmt = "could not find url param %s"
  12. urlParamErrUintConvFmt = "could not convert url parameter %s to uint, got %s"
  13. )
  14. // GetURLParamString returns a specific URL parameter as a string using
  15. // chi.URLParam. It returns an internal server error if the URL parameter is not found.
  16. func GetURLParamString(r *http.Request, param types.URLParam) (string, apierrors.RequestError) {
  17. urlParam := chi.URLParam(r, string(param))
  18. if urlParam == "" {
  19. // this is an internal server error, since it means the handler requested an
  20. // invalid url parameter
  21. return "", apierrors.NewErrInternal(fmt.Errorf(urlParamNotFoundFmt, param))
  22. }
  23. return urlParam, nil
  24. }
  25. // GetURLParamUint returns a URL parameter as a uint. It returns
  26. // an internal server error if the URL parameter is not found.
  27. func GetURLParamUint(r *http.Request, param types.URLParam) (uint, apierrors.RequestError) {
  28. urlParam, reqErr := GetURLParamString(r, param)
  29. if reqErr != nil {
  30. return 0, reqErr
  31. }
  32. res64, err := strconv.ParseUint(urlParam, 10, 64)
  33. if err != nil {
  34. return 0, apierrors.NewErrPassThroughToClient(
  35. fmt.Errorf(urlParamErrUintConvFmt, param, urlParam),
  36. http.StatusBadRequest,
  37. )
  38. }
  39. return uint(res64), nil
  40. }