2015-03-29 21:17:23 +00:00
|
|
|
package httputils
|
|
|
|
|
|
|
|
import (
|
2015-06-04 13:30:14 +00:00
|
|
|
"errors"
|
2015-03-29 21:17:23 +00:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2015-06-04 13:30:14 +00:00
|
|
|
"regexp"
|
|
|
|
"strings"
|
2015-03-29 21:17:23 +00:00
|
|
|
|
|
|
|
"github.com/docker/docker/pkg/jsonmessage"
|
|
|
|
)
|
|
|
|
|
2015-08-03 01:45:05 +00:00
|
|
|
// Download requests a given URL and returns an io.Reader.
|
2015-03-29 21:17:23 +00:00
|
|
|
func Download(url string) (resp *http.Response, err error) {
|
|
|
|
if resp, err = http.Get(url); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if resp.StatusCode >= 400 {
|
|
|
|
return nil, fmt.Errorf("Got HTTP status code >= 400: %s", resp.Status)
|
|
|
|
}
|
|
|
|
return resp, nil
|
|
|
|
}
|
|
|
|
|
2015-08-03 01:45:05 +00:00
|
|
|
// NewHTTPRequestError returns a JSON response error.
|
2015-03-29 21:17:23 +00:00
|
|
|
func NewHTTPRequestError(msg string, res *http.Response) error {
|
|
|
|
return &jsonmessage.JSONError{
|
|
|
|
Message: msg,
|
|
|
|
Code: res.StatusCode,
|
|
|
|
}
|
|
|
|
}
|
2015-06-04 13:30:14 +00:00
|
|
|
|
2015-08-03 01:45:05 +00:00
|
|
|
// ServerHeader contains the server information.
|
2015-06-04 13:30:14 +00:00
|
|
|
type ServerHeader struct {
|
|
|
|
App string // docker
|
|
|
|
Ver string // 1.8.0-dev
|
|
|
|
OS string // windows or linux
|
|
|
|
}
|
|
|
|
|
2015-08-03 01:45:05 +00:00
|
|
|
// ParseServerHeader extracts pieces from an HTTP server header
|
|
|
|
// which is in the format "docker/version (os)" eg docker/1.8.0-dev (windows).
|
2015-06-04 13:30:14 +00:00
|
|
|
func ParseServerHeader(hdr string) (*ServerHeader, error) {
|
|
|
|
re := regexp.MustCompile(`.*\((.+)\).*$`)
|
|
|
|
r := &ServerHeader{}
|
|
|
|
if matches := re.FindStringSubmatch(hdr); matches != nil {
|
|
|
|
r.OS = matches[1]
|
|
|
|
parts := strings.Split(hdr, "/")
|
|
|
|
if len(parts) != 2 {
|
|
|
|
return nil, errors.New("Bad header: '/' missing")
|
|
|
|
}
|
|
|
|
r.App = parts[0]
|
|
|
|
v := strings.Split(parts[1], " ")
|
|
|
|
if len(v) != 2 {
|
|
|
|
return nil, errors.New("Bad header: Expected single space")
|
|
|
|
}
|
|
|
|
r.Ver = v[0]
|
|
|
|
return r, nil
|
|
|
|
}
|
|
|
|
return nil, errors.New("Bad header: Failed regex match")
|
|
|
|
}
|