github.com/slene/docker@v1.8.0-rc1/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  // Download requests a given URL and returns an io.Reader
    14  func Download(url string) (resp *http.Response, err error) {
    15  	if resp, err = http.Get(url); err != nil {
    16  		return nil, err
    17  	}
    18  	if resp.StatusCode >= 400 {
    19  		return nil, fmt.Errorf("Got HTTP status code >= 400: %s", resp.Status)
    20  	}
    21  	return resp, nil
    22  }
    23  
    24  // NewHTTPRequestError returns a JSON response error
    25  func NewHTTPRequestError(msg string, res *http.Response) error {
    26  	return &jsonmessage.JSONError{
    27  		Message: msg,
    28  		Code:    res.StatusCode,
    29  	}
    30  }
    31  
    32  type ServerHeader struct {
    33  	App string // docker
    34  	Ver string // 1.8.0-dev
    35  	OS  string // windows or linux
    36  }
    37  
    38  // parseServerHeader extracts pieces from am HTTP server header
    39  // which is in the format "docker/version (os)" eg docker/1.8.0-dev (windows)
    40  func ParseServerHeader(hdr string) (*ServerHeader, error) {
    41  	re := regexp.MustCompile(`.*\((.+)\).*$`)
    42  	r := &ServerHeader{}
    43  	if matches := re.FindStringSubmatch(hdr); matches != nil {
    44  		r.OS = matches[1]
    45  		parts := strings.Split(hdr, "/")
    46  		if len(parts) != 2 {
    47  			return nil, errors.New("Bad header: '/' missing")
    48  		}
    49  		r.App = parts[0]
    50  		v := strings.Split(parts[1], " ")
    51  		if len(v) != 2 {
    52  			return nil, errors.New("Bad header: Expected single space")
    53  		}
    54  		r.Ver = v[0]
    55  		return r, nil
    56  	}
    57  	return nil, errors.New("Bad header: Failed regex match")
    58  }