-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
91 lines (81 loc) · 1.92 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
85
86
87
88
89
90
91
package sypht
import (
"fmt"
"net/http"
"os"
"strings"
"sync"
"time"
)
/*
Client to the HTTP API of Sypht.
*/
// Client ...
type Client struct {
httpClient *http.Client
config *config
apiToken string
tokenUpdatedAt time.Time
mutex sync.RWMutex
}
type config struct {
clientID string
clientSecret string
apiBaseURL string
authURL string
}
var defaultTimeout = 30
// fieldSets const
const (
Generic = "\"sypht.generic\""
Document = "\"sypht.document\""
Invoice = "\"sypht.invoice\""
Bill = "\"sypht.bill\""
Bank = "\"sypht.bank\""
)
//NewSyphtClient returns a Sypht client instance,
// default request timeout is set to 30 seconds, change it as needed
func NewSyphtClient(apiKey string, timeout *int) (client *Client, err error) {
authURL := os.Getenv("SYPHT_AUTH_ENDPOINT")
if authURL == "" {
authURL = "https://login.sypht.com/oauth/token"
}
if timeout == nil || *timeout < 0 {
timeout = &defaultTimeout
}
clientID, clientSecret, err := processAPIKey(apiKey)
if err != nil {
return
}
client = &Client{
httpClient: &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Timeout: time.Second * time.Duration(*timeout),
},
config: &config{
clientID: clientID,
clientSecret: clientSecret,
apiBaseURL: "https://api.sypht.com",
authURL: authURL,
},
}
_, err = client.RefreshToken()
return
}
//NewSyphtClientFromEnv same as NewSyphtClient except it reads creds from ENV
func NewSyphtClientFromEnv(timeout *int) (client *Client, err error) {
client, err = NewSyphtClient(os.Getenv("SYPHT_API_KEY"), timeout)
return
}
func processAPIKey(apiKey string) (clientID string, clientSecret string, err error) {
arr := strings.Split(apiKey, ":")
if len(arr) != 2 {
err = fmt.Errorf("invalid apikey %s", apiKey)
return
}
clientID = arr[0]
clientSecret = arr[1]
return
}