param.go 1.3 KB

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