2015-03-29 17:17:23 -04:00
|
|
|
package httputils
|
|
|
|
|
|
|
|
import (
|
2015-06-04 09:30:14 -04:00
|
|
|
"errors"
|
2015-03-29 17:17:23 -04:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2015-06-04 09:30:14 -04:00
|
|
|
"regexp"
|
2015-08-28 14:54:44 -04:00
|
|
|
"strings"
|
2015-03-29 17:17:23 -04:00
|
|
|
|
|
|
|
"github.com/docker/docker/pkg/jsonmessage"
|
|
|
|
)
|
|
|
|
|
2015-08-28 11:03:04 -04:00
|
|
|
var (
|
2015-08-28 14:54:44 -04:00
|
|
|
headerRegexp = regexp.MustCompile(`^(?:(.+)/(.+?))\((.+)\).*$`)
|
2015-08-28 11:03:04 -04:00
|
|
|
errInvalidHeader = errors.New("Bad header, should be in format `docker/version (platform)`")
|
|
|
|
)
|
|
|
|
|
2015-08-02 21:45:05 -04:00
|
|
|
// Download requests a given URL and returns an io.Reader.
|
2015-03-29 17:17:23 -04: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-02 21:45:05 -04:00
|
|
|
// NewHTTPRequestError returns a JSON response error.
|
2015-03-29 17:17:23 -04:00
|
|
|
func NewHTTPRequestError(msg string, res *http.Response) error {
|
|
|
|
return &jsonmessage.JSONError{
|
|
|
|
Message: msg,
|
|
|
|
Code: res.StatusCode,
|
|
|
|
}
|
|
|
|
}
|
2015-06-04 09:30:14 -04:00
|
|
|
|
2015-08-02 21:45:05 -04:00
|
|
|
// ServerHeader contains the server information.
|
2015-06-04 09:30:14 -04:00
|
|
|
type ServerHeader struct {
|
|
|
|
App string // docker
|
|
|
|
Ver string // 1.8.0-dev
|
|
|
|
OS string // windows or linux
|
|
|
|
}
|
|
|
|
|
2015-08-02 21:45:05 -04: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 09:30:14 -04:00
|
|
|
func ParseServerHeader(hdr string) (*ServerHeader, error) {
|
2015-08-28 11:03:04 -04:00
|
|
|
matches := headerRegexp.FindStringSubmatch(hdr)
|
|
|
|
if len(matches) != 4 {
|
|
|
|
return nil, errInvalidHeader
|
2015-06-04 09:30:14 -04:00
|
|
|
}
|
2015-08-28 11:03:04 -04:00
|
|
|
return &ServerHeader{
|
2015-08-28 14:54:44 -04:00
|
|
|
App: strings.TrimSpace(matches[1]),
|
|
|
|
Ver: strings.TrimSpace(matches[2]),
|
|
|
|
OS: strings.TrimSpace(matches[3]),
|
2015-08-28 11:03:04 -04:00
|
|
|
}, nil
|
2015-06-04 09:30:14 -04:00
|
|
|
}
|