-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
91 lines (74 loc) · 1.64 KB
/
client.go
File metadata and controls
91 lines (74 loc) · 1.64 KB
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
/**
Copyright Contributors to the Feilong Project.
SPDX-License-Identifier: Apache-2.0
**/
package feilong
import (
"fmt"
"bytes"
"io/ioutil"
"net/http"
"time"
)
const defaultConnector string = "localhost:35000"
const defaultTimeout time.Duration = 300 * time.Second
type Client struct {
Host string
HTTPClient *http.Client
Token *string
}
func NewClient(connector *string, timeout *time.Duration) (*Client) {
h := defaultConnector
if connector != nil {
h = *connector
}
t := defaultTimeout
if timeout != nil {
t = *timeout
}
c := Client{
HTTPClient: &http.Client{Timeout: t},
Host: h,
Token: nil,
}
return &c
}
// For internal use
func (c *Client) doRequest(method string, path string, params []byte) ([]byte, error) {
url := c.Host + path
reader := bytes.NewReader(params)
req, err := http.NewRequest(method, url, reader)
if err != nil {
return nil, err
}
contentType := "application/json"
if method == "PUT" && path == "/files" {
contentType = "application/octet-stream"
}
req.Header.Add("Content-Type", contentType)
if c.Token != nil {
if method == "POST" && path == "/token" {
req.Header.Add("X-Admin-Token", *c.Token)
} else {
req.Header.Add("X-Auth-Token", *c.Token)
}
}
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 {
return nil, fmt.Errorf("HTTP status: %d, body: %s", res.StatusCode, body)
}
if c.Token != nil {
if method == "POST" && path == "/token" {
*c.Token = res.Header.Get("X-Auth-Token")
}
}
return body, nil
}