form.go 2.1 KB

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