-
Notifications
You must be signed in to change notification settings - Fork 31
/
witai.go
99 lines (80 loc) · 2.2 KB
/
witai.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
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
package witai
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
const (
DefaultVersion = "20240304"
WitTimeFormat = "2006-01-02T15:04:05Z0700"
)
// Client - Wit.ai client type
type Client struct {
APIBase string
Token string
Version string
headerAuth string
headerAccept string
httpClient *http.Client
}
type errorResp struct {
Body string `json:"body"`
Error string `json:"error"`
}
// NewClient returns client for default API version
func NewClient(token string) *Client {
return newClientWithVersion(token, DefaultVersion)
}
// SetHTTPClient allows to use your custom http.Client
func (c *Client) SetHTTPClient(httpClient *http.Client) {
c.httpClient = httpClient
}
func newClientWithVersion(token, version string) *Client {
headerAuth := fmt.Sprintf("Bearer %s", token)
headerAccept := fmt.Sprintf("application/vnd.wit.%s+json", version)
defaultClient := &http.Client{
Timeout: time.Second * 10,
}
return &Client{
APIBase: "https://api.wit.ai",
Token: token,
Version: version,
headerAuth: headerAuth,
headerAccept: headerAccept,
httpClient: defaultClient,
}
}
func (c *Client) request(method, url string, ct string, body io.Reader) (io.ReadCloser, error) {
req, err := http.NewRequest(method, c.APIBase+url, body)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", c.headerAuth)
req.Header.Set("Accept", c.headerAccept)
req.Header.Set("Content-Type", ct)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode >= http.StatusBadRequest {
defer resp.Body.Close()
var e *errorResp
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&e)
if err != nil {
return nil, fmt.Errorf("unable to decode error message: %s", err.Error())
}
// Wit.ai errors sometimes have "error", sometimes "body" message
if len(e.Error) > 0 {
return nil, fmt.Errorf("unable to make a request. error: %s", e.Error)
}
if len(e.Body) > 0 {
return nil, fmt.Errorf("unable to make a request. error: %s", e.Body)
}
return nil, fmt.Errorf("unable to make a request. error: %v", e)
}
return resp.Body, nil
}