-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
135 lines (109 loc) · 2.5 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package tika
import (
"encoding/json"
"io"
"io/ioutil"
"net"
"net/http"
"time"
"github.com/Sirupsen/logrus"
)
const userAgent = "go-tika-client"
// Client represents the structure of the client for interacting with the Tika Rest API
type Client struct {
httpClient *http.Client
Document io.Reader
DocumentName string
Key string
Options
}
// Options represents the structure of the options for the Client
type Options struct {
Url string
}
// NewRequest returns a new http.Request
func (c *Client) NewRequest(method, endpoint string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, endpoint, body)
if err != nil {
return nil, err
}
return req, nil
}
// Do makes an HTTP request and returns bytes
func (c *Client) Do(req *http.Request) ([]byte, error) {
req.Header.Set("User-Agent", userAgent)
res, getErr := c.httpClient.Do(req)
if getErr != nil {
return nil, getErr
}
if res.StatusCode != 200 {
logrus.Fatalf("Status: %s", res.Status)
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
return nil, readErr
}
return body, nil
}
// NewClient takes Options and returns a Client with the
func NewClient(options *Options) *Client {
var netTransport = &http.Transport{
Dial: (&net.Dialer{
Timeout: 5 * time.Second,
}).Dial,
TLSHandshakeTimeout: 5 * time.Second,
}
var netClient = &http.Client{
Timeout: time.Second * 10,
Transport: netTransport,
}
return &Client{
httpClient: netClient,
Options: *options,
}
}
func (c *Client) csv(req *http.Request) (string, error) {
req.Header.Set("Accept", "text/csv")
res, err := c.Do(req)
if err != nil {
return "", err
}
return string(res), nil
}
func (c *Client) html(req *http.Request) (string, error) {
req.Header.Set("Accept", "text/html")
res, err := c.Do(req)
if err != nil {
return "", err
}
return string(res), nil
}
func (c *Client) json(req *http.Request) ([]byte, error) {
req.Header.Set("Accept", "application/json")
res, err := c.Do(req)
if err != nil {
return nil, err
}
var raw map[string]interface{}
json.Unmarshal(res, &raw)
out, err := json.Marshal(raw)
if err != nil {
return nil, err
}
return out, err
}
func (c *Client) raw(req *http.Request) ([]byte, error) {
res, err := c.Do(req)
if err != nil {
return nil, err
}
return res, nil
}
func (c *Client) text(req *http.Request) (string, error) {
req.Header.Set("Accept", "text/plain")
res, err := c.Do(req)
if err != nil {
return "", err
}
return string(res), nil
}