/
http.go
168 lines (153 loc) · 4.04 KB
/
http.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// Copyright © 2017 Envoy Project <hello@envoyproject.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"time"
)
//Client stores the configuration of the client
type Client struct {
//Address points to the address of the searchhead api
Address string
//HTTPClient is the client to use. Default will be used if not provided
HTTPClient *http.Client
//Token is the authentication token to be used for the requests
Token string
}
//NewClient creates a new client, and gets a secure token
func NewClient() (*Client, error) {
diskconfig, err := readConfigFile()
if err != nil {
return nil, err
}
token, err := getSecureToken(diskconfig.EnvoyAddress, diskconfig.Username, diskconfig.Apikey)
if err != nil {
return nil, err
}
client := &Client{
Address: diskconfig.EnvoyAddress,
HTTPClient: &http.Client{
Transport: http.DefaultTransport,
},
Token: token,
}
return client, nil
}
// Request this maps a new request
type Request struct {
Method string
Path string
Values url.Values
Body io.Reader
}
//newRequest is used to make a new request
//and include the configuration data
func (c *Client) newRequest(r *Request) (*http.Request, error) {
uri := url.URL{
Scheme: "http",
Host: c.Address,
Path: r.Path,
//RawQuery: params.Encode
}
uri.RawQuery = r.Values.Encode()
//url.Query you can set parameters
req, err := http.NewRequest(r.Method, uri.RequestURI(), r.Body)
if err != nil {
return nil, err
}
req.URL.Scheme = uri.Scheme
req.URL.Host = uri.Host
req.Host = uri.Host
req.Header.Set("X-Envoy-Token", c.Token)
return req, nil
}
//doRequest performs the request
func (c *Client) doRequest(r *http.Request) (time.Duration, *http.Response, error) {
//output the request if needed
if debug {
if err := dumpRequest(r); err != nil {
log.Fatal(err)
}
}
start := time.Now()
resp, err := c.HTTPClient.Do(r)
diff := time.Now().Sub(start)
return diff, resp, err
}
// decodeBody is used to JSON decode a body
func decodeBody(resp *http.Response, out interface{}) error {
dec := json.NewDecoder(resp.Body)
return dec.Decode(out)
}
// encodeBody is used to encode a request body
func encodeBody(obj interface{}) (io.Reader, error) {
buf := bytes.NewBuffer(nil)
enc := json.NewEncoder(buf)
if err := enc.Encode(obj); err != nil {
return nil, err
}
return buf, nil
}
//dumpRequest outputs the request for debugging
func dumpRequest(r *http.Request) error {
dump, err := httputil.DumpRequestOut(r, true)
if err != nil {
fmt.Println(err)
return err
}
fmt.Printf("%q", dump)
return nil
}
//getSecureToken gets a temporary token to perform operations
func getSecureToken(backend, username, apikey string) (string, error) {
apilogin := struct {
Username string `json:"username"`
Apikey string `json:"apikey"`
}{
Username: username,
Apikey: apikey,
}
enc, err := json.Marshal(apilogin)
if err != nil {
return "", err
}
url := fmt.Sprintf("http://%s/api/apisignin", backend)
resp, err := http.Post(url, "application/json", bytes.NewReader(enc))
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
//handleError(resp)
return "", fmt.Errorf("response error code: %d", resp.StatusCode)
}
type apiResponse struct {
Token string `json:"token"`
Username string `json:"username"`
ID int64 `json:"id"`
Apikey string `json:"apikey"`
}
var data apiResponse
if err = decodeBody(resp, &data); err != nil {
return "", err
}
return data.Token, nil
}