/
http.go
72 lines (59 loc) · 1.53 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
package idmappers
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/danielkraic/idmapper/idmapper"
"github.com/sirupsen/logrus"
)
// NewHTTPIDMapper creates IDMapper that reads data from http
func NewHTTPIDMapper(log *logrus.Logger, url string, timeout time.Duration) (*idmapper.IDMapper, error) {
if url == "" {
return nil, fmt.Errorf("failed to create HTTP IDMapper: empty url")
}
return idmapper.NewIDMapper(&httpSource{
url: url,
log: log,
})
}
type httpSource struct {
log *logrus.Logger
url string
timeout time.Duration
}
type httpSourceResponse struct {
ID string `json:"id"`
Name string `json:"name"`
}
func (source httpSource) Read() (idmapper.ValuesMap, error) {
result := make(idmapper.ValuesMap)
client := http.Client{
Timeout: source.timeout,
CheckRedirect: nil,
}
httpResponse, err := client.Get(source.url)
if err != nil {
return result, fmt.Errorf("failed to get url %s: %s", source.url, err)
}
defer func() {
err = httpResponse.Body.Close()
if err != nil {
source.log.Errorf("failed to close http body: %s", err)
}
}()
body, err := ioutil.ReadAll(httpResponse.Body)
if err != nil {
return result, fmt.Errorf("failed to read response from url %s: %s", source.url, err)
}
var responseData []httpSourceResponse
err = json.Unmarshal(body, &responseData)
if err != nil {
return result, fmt.Errorf("failed to decode json from url %s: %s", source.url, err)
}
for _, item := range responseData {
result[item.ID] = item.Name
}
return result, nil
}