github.com/mwhudson/juju@v0.0.0-20160512215208-90ff01f3497f/downloader/utils.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package downloader
     5  
     6  import (
     7  	"io"
     8  	"net/http"
     9  	"net/url"
    10  	"os"
    11  
    12  	"github.com/juju/errors"
    13  	"github.com/juju/utils"
    14  )
    15  
    16  // NewHTTPBlobOpener returns a blob opener func suitable for use with
    17  // Download. The opener func uses an HTTP client that enforces the
    18  // provided SSL hostname verification policy.
    19  func NewHTTPBlobOpener(hostnameVerification utils.SSLHostnameVerification) func(*url.URL) (io.ReadCloser, error) {
    20  	return func(url *url.URL) (io.ReadCloser, error) {
    21  		// TODO(rog) make the download operation interruptible.
    22  		client := utils.GetHTTPClient(hostnameVerification)
    23  		resp, err := client.Get(url.String())
    24  		if err != nil {
    25  			return nil, err
    26  		}
    27  		if resp.StatusCode != http.StatusOK {
    28  			// resp.Body is always non-nil. (see https://golang.org/pkg/net/http/#Response)
    29  			resp.Body.Close()
    30  			return nil, errors.Errorf("bad http response: %v", resp.Status)
    31  		}
    32  		return resp.Body, nil
    33  	}
    34  }
    35  
    36  // NewSha256Verifier returns a verifier suitable for Request. The
    37  // verifier checks the SHA-256 checksum of the file to ensure that it
    38  // matches the one returned by the provided func.
    39  func NewSha256Verifier(expected string) func(*os.File) error {
    40  	return func(file *os.File) error {
    41  		actual, _, err := utils.ReadSHA256(file)
    42  		if err != nil {
    43  			return errors.Trace(err)
    44  		}
    45  		if actual != expected {
    46  			err := errors.Errorf("expected sha256 %q, got %q", expected, actual)
    47  			return errors.NewNotValid(err, "")
    48  		}
    49  		return nil
    50  	}
    51  }