/
client.go
114 lines (94 loc) · 2.72 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package tableau
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
)
type Client struct {
ApiUrl string
HTTPClient *http.Client
AuthToken string
}
type Site struct {
ID *string `json:"id"`
ContentUrl string `json:"contentUrl"`
}
type Credentials struct {
Name *string `json:"name"`
Password *string `json:"password"`
TokenName *string `json:"personalAccessTokenName"`
TokenSecret *string `json:"personalAccessTokenSecret"`
Site Site `json:"site"`
}
type SignInRequest struct {
Credentials Credentials `json:"credentials"`
}
type SignInResponseData struct {
Site Site `json:"site"`
User User `json:"user"`
Token string `json:"token"`
EstimatedTimeToExpiration string `json:"estimatedTimeToExpiration"`
}
type SignInResponse struct {
SignInResponseData SignInResponseData `json:"credentials"`
}
func NewClient(server, username, password, personalAccessTokenName, personalAccessTokenSecret, site, serverVersion *string) (*Client, error) {
c := Client{
HTTPClient: &http.Client{Timeout: 10 * time.Second},
}
if (server != nil) && (username != nil) && (site != nil) && (serverVersion != nil) {
baseUrl := fmt.Sprintf("%s/api/%s", *server, *serverVersion)
url := fmt.Sprintf("%s/auth/signin", baseUrl)
siteStruct := Site{ContentUrl: *site}
credentials := Credentials{
Name: username,
Password: password,
TokenName: personalAccessTokenName,
TokenSecret: personalAccessTokenSecret,
Site: siteStruct,
}
authRequest := SignInRequest{
Credentials: credentials,
}
authRequestJson, err := json.Marshal(authRequest)
if err != nil {
return nil, err
}
// authenticate
req, err := http.NewRequest("POST", url, strings.NewReader(string(authRequestJson)))
if err != nil {
return nil, err
}
body, err := c.doRequest(req)
// parse response body
ar := SignInResponse{}
err = json.Unmarshal(body, &ar)
if err != nil {
return nil, err
}
c.ApiUrl = fmt.Sprintf("%s/sites/%s", baseUrl, *ar.SignInResponseData.Site.ID)
c.AuthToken = ar.SignInResponseData.Token
}
return &c, nil
}
func (c *Client) doRequest(req *http.Request) ([]byte, error) {
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("X-Tableau-Auth", c.AuthToken)
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
if (res.StatusCode != http.StatusOK) && (res.StatusCode != 201) && (res.StatusCode != 204) {
return nil, fmt.Errorf("status: %d, body: %s", res.StatusCode, body)
}
return body, err
}