From 0d00bf9fd242d3b4f9f3d6caaf5a61f8a3627d7f Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Tue, 28 May 2024 13:13:13 +0200 Subject: [golang] fixed golang api client design mistakes --- golang/pkg/api/client.go | 56 +++++++++++++----------------------------------- 1 file changed, 15 insertions(+), 41 deletions(-) (limited to 'golang/pkg/api/client.go') diff --git a/golang/pkg/api/client.go b/golang/pkg/api/client.go index 70f3e68..2ea555e 100644 --- a/golang/pkg/api/client.go +++ b/golang/pkg/api/client.go @@ -4,25 +4,30 @@ import ( "container/heap" "context" "net/http" + "net/url" "time" ) type Client struct { - baseURL string - channel chan *Request - ctx context.Context - headers *http.Header - httpClient *http.Client - pq *PriorityQueue + baseURI *url.URL + requestsChannel chan *Request + ctx context.Context + headers *http.Header + httpClient *http.Client + pq *PriorityQueue } func NewClient(ctx context.Context) *Client { + baseURI, err := url.Parse("https://api.spacetraders.io/v2/") + if err != nil { + panic("baseURI failed to parse") + } pq := make(PriorityQueue, 0) heap.Init(&pq) client := &Client{ - baseURL: "https://api.spacetraders.io/v2", - channel: make(chan *Request), - ctx: ctx, + baseURI: baseURI, + requestsChannel: make(chan *Request), + ctx: ctx, headers: &http.Header{ "Content-Type": {"application/json"}, }, @@ -36,40 +41,9 @@ func NewClient(ctx context.Context) *Client { } func (c *Client) Close() { - close(c.channel) + close(c.requestsChannel) } func (c *Client) SetToken(token string) { c.headers.Set("Authorization", "Bearer "+token) } - -func queueProcessor(client *Client) { - var ok bool - for { - // The queue is empty so we do this blocking call - req := <-client.channel - heap.Push(client.pq, req) - // we enqueue all values read from the channel and process the queue's - // contents until empty. We keep reading the channel as long as this - // emptying goes on - for { - select { - case req = <-client.channel: - heap.Push(client.pq, req) - default: - if client.pq.Len() == 0 { - break - } - // we process one - if req, ok = heap.Pop(client.pq).(*Request); !ok { - panic("queueProcessor got something other than a Request on its channel") - } - response, err := client.sendOne(req.method, req.path, req.payload) - req.resp <- &Response{ - Response: response, - Err: err, - } - } - } - } -} -- cgit v1.2.3