httputils.go 1.5 KB

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