form.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package httputils
  2. import (
  3. "errors"
  4. "net/http"
  5. "path/filepath"
  6. "strconv"
  7. "strings"
  8. )
  9. // BoolValue transforms a form value in different formats into a boolean type.
  10. func BoolValue(r *http.Request, k string) bool {
  11. s := strings.ToLower(strings.TrimSpace(r.FormValue(k)))
  12. return !(s == "" || s == "0" || s == "no" || s == "false" || s == "none")
  13. }
  14. // BoolValueOrDefault returns the default bool passed if the query param is
  15. // missing, otherwise it's just a proxy to boolValue above.
  16. func BoolValueOrDefault(r *http.Request, k string, d bool) bool {
  17. if _, ok := r.Form[k]; !ok {
  18. return d
  19. }
  20. return BoolValue(r, k)
  21. }
  22. // Int64ValueOrZero parses a form value into an int64 type.
  23. // It returns 0 if the parsing fails.
  24. func Int64ValueOrZero(r *http.Request, k string) int64 {
  25. val, err := Int64ValueOrDefault(r, k, 0)
  26. if err != nil {
  27. return 0
  28. }
  29. return val
  30. }
  31. // Int64ValueOrDefault parses a form value into an int64 type. If there is an
  32. // error, returns the error. If there is no value returns the default value.
  33. func Int64ValueOrDefault(r *http.Request, field string, def int64) (int64, error) {
  34. if r.Form.Get(field) != "" {
  35. value, err := strconv.ParseInt(r.Form.Get(field), 10, 64)
  36. return value, err
  37. }
  38. return def, nil
  39. }
  40. // ArchiveOptions stores archive information for different operations.
  41. type ArchiveOptions struct {
  42. Name string
  43. Path string
  44. }
  45. // ArchiveFormValues parses form values and turns them into ArchiveOptions.
  46. // It fails if the archive name and path are not in the request.
  47. func ArchiveFormValues(r *http.Request, vars map[string]string) (ArchiveOptions, error) {
  48. if err := ParseForm(r); err != nil {
  49. return ArchiveOptions{}, err
  50. }
  51. name := vars["name"]
  52. path := filepath.FromSlash(r.Form.Get("path"))
  53. switch {
  54. case name == "":
  55. return ArchiveOptions{}, errors.New("bad parameter: 'name' cannot be empty")
  56. case path == "":
  57. return ArchiveOptions{}, errors.New("bad parameter: 'path' cannot be empty")
  58. }
  59. return ArchiveOptions{name, path}, nil
  60. }