github.com/hoffie/larasync@v0.0.0-20151025221940-0384d2bddcef/api/client/client.go (about)

     1  package client
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/hoffie/larasync/api/tls"
     7  )
     8  
     9  // Client provides convenience methods for accessing an api.Server
    10  // over HTTP.
    11  type Client struct {
    12  	http              *http.Client
    13  	BaseURL           string
    14  	netloc            string
    15  	adminSecret       []byte
    16  	signingPrivateKey [PrivateKeySize]byte
    17  }
    18  
    19  // NetlocToURL returns the URL matching the given netloc
    20  func NetlocToURL(netloc, repoName string) string {
    21  	// IMPROVEMENT: use mux router to generate URLs
    22  	return "https://" + netloc + "/repositories/" + repoName
    23  }
    24  
    25  // New returns a new Client instance.
    26  func New(url, fingerprint string, fingerprintVerifier tls.VerificationFunc) *Client {
    27  	fpv := tls.FingerprintVerifier{
    28  		AcceptFingerprint: fingerprint,
    29  		VerificationFunc:  fingerprintVerifier,
    30  	}
    31  	tr := &http.Transport{
    32  		DialTLS: fpv.DialTLS,
    33  	}
    34  	return &Client{
    35  		http:    &http.Client{Transport: tr},
    36  		BaseURL: url,
    37  	}
    38  }
    39  
    40  // SetAdminSecret sets the admin secret to use (e.g. for Register()).
    41  func (c *Client) SetAdminSecret(s []byte) {
    42  	c.adminSecret = s
    43  }
    44  
    45  // SetSigningPrivateKey sets the signing private key to use
    46  func (c *Client) SetSigningPrivateKey(k [PrivateKeySize]byte) {
    47  	c.signingPrivateKey = k
    48  }
    49  
    50  // doRequest executes the given request and verifies the resulting status code
    51  func (c *Client) doRequest(req *http.Request, expStatus ...int) (*http.Response, error) {
    52  	resp, err := c.http.Do(req)
    53  	if err != nil {
    54  		return nil, err
    55  	}
    56  	for _, expStatus := range expStatus {
    57  		if resp.StatusCode == expStatus {
    58  			return resp, nil
    59  		}
    60  	}
    61  	Log.Error("unexpected status", "got", resp.StatusCode, "wanted", expStatus)
    62  	return nil, ErrUnexpectedStatus
    63  }