-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
84 lines (69 loc) · 2 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package netpalmgo
import (
"context"
"go.bnck.me/netpalm/apis/getconfig"
"go.bnck.me/netpalm/apis/setconfig"
"go.bnck.me/netpalm/apis/task"
"go.bnck.me/netpalm/internal/transport"
"go.bnck.me/netpalm/models"
"net/http"
"sync"
"time"
)
// Client is the main client of netpalmgo
type Client struct {
transport *transport.Client
getConfig getconfig.Client
setConfig setconfig.Client
task task.Client
}
// New creates a new Client with APIUrl and APIKey
func New(apiURL, apiKey string) *Client {
return NewWithClient(apiURL, apiKey, nil)
}
// NewWithClient creates a new Client with APIUrl and APIKey with a given http.Client
func NewWithClient(apiURL, apiKey string, httpClient *http.Client) *Client {
c := Client{
transport: transport.NewClient(apiURL, apiKey, httpClient),
}
c.getConfig = getconfig.New(c.transport)
c.setConfig = setconfig.New(c.transport)
c.task = task.New(c.transport)
return &c
}
// WaitForResult waits blocking for the result to finish (also fail).
func (c *Client) WaitForResult(ctx context.Context, response *models.Response) (*models.Response, error) {
wg := sync.WaitGroup{}
resp := response
var err error
// wait for task to finish in other goroutine
wg.Add(1)
go func() {
defer wg.Done()
// sleep for 2 sec if task is not finished or failed and then check status again
for resp.Data.TaskStatus != models.TaskStatusFinished && resp.Data.TaskStatus != models.TaskStatusFailed {
resp, err = c.Task().WithTaskResponse(ctx, resp.Data)
if err != nil { // exit when error occurs
return
}
time.Sleep(2 * time.Second)
}
}()
wg.Wait()
if err != nil {
return nil, err
}
return resp, err
}
// GetConfig returns the client for the Endpoint /getconfig
func (c *Client) GetConfig() getconfig.Client {
return c.getConfig
}
// SetConfig returns the client for the Endpoint /setconfig
func (c *Client) SetConfig() setconfig.Client {
return c.setConfig
}
// Task returns the client for the Endpoint /task
func (c *Client) Task() task.Client {
return c.task
}