form.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package httputils
  2. import (
  3. "fmt"
  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. if err != nil {
  37. return value, err
  38. }
  39. return value, nil
  40. }
  41. return def, nil
  42. }
  43. // ArchiveOptions stores archive information for different operations.
  44. type ArchiveOptions struct {
  45. Name string
  46. Path string
  47. }
  48. // ArchiveFormValues parses form values and turns them into ArchiveOptions.
  49. // It fails if the archive name and path are not in the request.
  50. func ArchiveFormValues(r *http.Request, vars map[string]string) (ArchiveOptions, error) {
  51. if err := ParseForm(r); err != nil {
  52. return ArchiveOptions{}, err
  53. }
  54. name := vars["name"]
  55. path := filepath.FromSlash(r.Form.Get("path"))
  56. switch {
  57. case name == "":
  58. return ArchiveOptions{}, fmt.Errorf("bad parameter: 'name' cannot be empty")
  59. case path == "":
  60. return ArchiveOptions{}, fmt.Errorf("bad parameter: 'path' cannot be empty")
  61. }
  62. return ArchiveOptions{name, path}, nil
  63. }