github.com/ncdc/docker@v0.10.1-0.20160129113957-6c6729ef5b74/api/server/httputils/form.go (about)

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