github.com/flavio/docker@v0.1.3-0.20170117145210-f63d1a6eec47/api/server/httputils/form.go (about)

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