-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexoffice.go
75 lines (61 loc) · 1.56 KB
/
lexoffice.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
// This module implements a Go REST API client for the public API from lexoffice.
package lexoffice
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
const (
lexofficeBaseUrlV1 = "https://api.lexoffice.io/v1"
lexofficeDebugOutput = false
lexofficeTimeoutMinutes = 5
)
type Client struct {
apiKey string
baseURL string
debug bool
HTTPClient *http.Client
}
// NewClient creates new lexoffice.io client with given API key
func NewClient(apiKey string) *Client {
return &Client{
apiKey: apiKey,
baseURL: lexofficeBaseUrlV1,
debug: lexofficeDebugOutput,
HTTPClient: &http.Client{
Timeout: lexofficeTimeoutMinutes * time.Minute,
},
}
}
type errorResponse struct {
Message string `json:"message"`
}
// Content-type and body should be already added to req
func (c *Client) sendRequest(req *http.Request, result interface{}) error {
req.Header.Set("Accept", "application/json; charset=utf-8")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.apiKey))
if c.debug {
fmt.Printf("\n%s\n\n", prettyPrintRequest(req))
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if c.debug {
fmt.Printf("\n%s\n\n", prettyPrintResponse(res))
}
if res.StatusCode != http.StatusOK {
var errRes errorResponse
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
return errors.New(errRes.Message)
}
return fmt.Errorf("unknown error, status code: %d", res.StatusCode)
}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
return err
}
return nil
}