github.com/bitfinexcom/bitfinex-api-go@v0.0.0-20210608095005-9e0b26f200fb/v2/rest/transport.go (about)

     1  package rest
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"net/http"
     7  	"net/url"
     8  )
     9  
    10  type HttpTransport struct {
    11  	BaseURL    *url.URL
    12  	HTTPClient *http.Client
    13  	httpDo     func(c *http.Client, req *http.Request) (*http.Response, error)
    14  }
    15  
    16  func (h HttpTransport) Request(req Request) ([]interface{}, error) {
    17  	var raw []interface{}
    18  
    19  	rel, err := url.Parse(req.RefURL)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	if req.Params != nil {
    24  		rel.RawQuery = req.Params.Encode()
    25  	}
    26  	if req.Data == nil {
    27  		req.Data = []byte("{}")
    28  	}
    29  	body := bytes.NewReader(req.Data)
    30  
    31  	u := h.BaseURL.ResolveReference(rel)
    32  	httpReq, err := http.NewRequest(req.Method, u.String(), body)
    33  	for k, v := range req.Headers {
    34  		httpReq.Header.Add(k, v)
    35  	}
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  	err = h.do(httpReq, &raw)
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	return raw, nil
    45  }
    46  
    47  // Do executes API request created by NewRequest method or custom *http.Request.
    48  func (h HttpTransport) do(req *http.Request, v interface{}) (error) {
    49  	resp, err := h.httpDo(h.HTTPClient, req)
    50  	if err != nil {
    51  		return err
    52  	}
    53  	defer resp.Body.Close()
    54  
    55  	response := newResponse(resp)
    56  	err = checkResponse(response)
    57  	if err != nil {
    58  		return err
    59  	}
    60  
    61  	if v != nil {
    62  		err = json.Unmarshal(response.Body, v)
    63  		if err != nil {
    64  			return err
    65  		}
    66  	}
    67  
    68  	return nil
    69  }