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