github.com/docker/docker@v299999999.0.0-20200612211812-aaf470eca7b5+incompatible/api/server/httputils/form.go (about)

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