url_param.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 urlParamNotFoundFmt = "could not find url param %s"
  11. const urlParamErrUintConvFmt = "could not convert url parameter %s to uint, got %s"
  12. // GetURLParamString returns a specific URL parameter as a string using
  13. // chi.URLParam. It returns an internal server error if the URL parameter is not found.
  14. func GetURLParamString(r *http.Request, param types.URLParam) (string, apierrors.RequestError) {
  15. urlParam := chi.URLParam(r, string(param))
  16. if urlParam == "" {
  17. // this is an internal server error, since it means the handler requested an
  18. // invalid url parameter
  19. return "", apierrors.NewErrInternal(fmt.Errorf(urlParamNotFoundFmt, param))
  20. }
  21. return urlParam, nil
  22. }
  23. // GetURLParamUint returns a URL parameter as a uint. It returns
  24. // an internal server error if the URL parameter is not found.
  25. func GetURLParamUint(r *http.Request, param types.URLParam) (uint, apierrors.RequestError) {
  26. urlParam, reqErr := GetURLParamString(r, param)
  27. if reqErr != nil {
  28. return 0, reqErr
  29. }
  30. res64, err := strconv.ParseUint(urlParam, 10, 64)
  31. if err != nil {
  32. return 0, apierrors.NewErrPassThroughToClient(
  33. fmt.Errorf(urlParamErrUintConvFmt, param, urlParam),
  34. http.StatusBadRequest,
  35. )
  36. }
  37. return uint(res64), nil
  38. }