github.com/damirazo/docker@v1.9.0/pkg/httputils/httputils.go (about)

     1  package httputils
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"net/http"
     7  	"regexp"
     8  	"strings"
     9  
    10  	"github.com/docker/docker/pkg/jsonmessage"
    11  )
    12  
    13  var (
    14  	headerRegexp     = regexp.MustCompile(`^(?:(.+)/(.+?))\((.+)\).*$`)
    15  	errInvalidHeader = errors.New("Bad header, should be in format `docker/version (platform)`")
    16  )
    17  
    18  // Download requests a given URL and returns an io.Reader.
    19  func Download(url string) (resp *http.Response, err error) {
    20  	if resp, err = http.Get(url); err != nil {
    21  		return nil, err
    22  	}
    23  	if resp.StatusCode >= 400 {
    24  		return nil, fmt.Errorf("Got HTTP status code >= 400: %s", resp.Status)
    25  	}
    26  	return resp, nil
    27  }
    28  
    29  // NewHTTPRequestError returns a JSON response error.
    30  func NewHTTPRequestError(msg string, res *http.Response) error {
    31  	return &jsonmessage.JSONError{
    32  		Message: msg,
    33  		Code:    res.StatusCode,
    34  	}
    35  }
    36  
    37  // ServerHeader contains the server information.
    38  type ServerHeader struct {
    39  	App string // docker
    40  	Ver string // 1.8.0-dev
    41  	OS  string // windows or linux
    42  }
    43  
    44  // ParseServerHeader extracts pieces from an HTTP server header
    45  // which is in the format "docker/version (os)" eg docker/1.8.0-dev (windows).
    46  func ParseServerHeader(hdr string) (*ServerHeader, error) {
    47  	matches := headerRegexp.FindStringSubmatch(hdr)
    48  	if len(matches) != 4 {
    49  		return nil, errInvalidHeader
    50  	}
    51  	return &ServerHeader{
    52  		App: strings.TrimSpace(matches[1]),
    53  		Ver: strings.TrimSpace(matches[2]),
    54  		OS:  strings.TrimSpace(matches[3]),
    55  	}, nil
    56  }