github.com/wtfutil/wtf@v0.43.0/modules/stocks/finnhub/client.go (about)

     1  package finnhub
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  	"net/url"
     8  )
     9  
    10  // Client ..
    11  type Client struct {
    12  	symbols []string
    13  	apiKey  string
    14  }
    15  
    16  // NewClient ..
    17  func NewClient(symbols []string, apiKey string) *Client {
    18  	client := Client{
    19  		symbols: symbols,
    20  		apiKey:  apiKey,
    21  	}
    22  
    23  	return &client
    24  }
    25  
    26  // Getquote ..
    27  func (client *Client) Getquote() ([]Quote, error) {
    28  	quotes := []Quote{}
    29  
    30  	for _, s := range client.symbols {
    31  		resp, err := client.finnhubRequest(s)
    32  		if err != nil {
    33  			return quotes, err
    34  		}
    35  
    36  		var quote Quote
    37  		quote.Stock = s
    38  		err = json.NewDecoder(resp.Body).Decode(&quote)
    39  		if err != nil {
    40  			return quotes, err
    41  		}
    42  		quotes = append(quotes, quote)
    43  	}
    44  
    45  	return quotes, nil
    46  }
    47  
    48  /* -------------------- Unexported Functions -------------------- */
    49  
    50  var (
    51  	finnhubURL = &url.URL{Scheme: "https", Host: "finnhub.io", Path: "/api/v1/quote"}
    52  )
    53  
    54  func (client *Client) finnhubRequest(symbol string) (*http.Response, error) {
    55  	params := url.Values{}
    56  	params.Add("symbol", symbol)
    57  	params.Add("token", client.apiKey)
    58  
    59  	url := finnhubURL.ResolveReference(&url.URL{RawQuery: params.Encode()})
    60  
    61  	req, err := http.NewRequest("GET", url.String(), http.NoBody)
    62  	req.Header.Add("Accept", "application/json")
    63  	req.Header.Add("Content-Type", "application/json")
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  
    68  	httpClient := &http.Client{}
    69  	resp, err := httpClient.Do(req)
    70  	if err != nil {
    71  		return nil, err
    72  	}
    73  	defer func() { _ = resp.Body.Close() }()
    74  
    75  	if resp.StatusCode < 200 || resp.StatusCode > 299 {
    76  		return nil, fmt.Errorf(resp.Status)
    77  	}
    78  
    79  	return resp, nil
    80  }