-
Notifications
You must be signed in to change notification settings - Fork 1
/
gateway.go
56 lines (45 loc) · 1.12 KB
/
gateway.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
package catalog
import (
"encoding/json"
"fmt"
"github.com/hashicorp/go-retryablehttp"
"github.com/pejovski/wish-list/model"
"github.com/sirupsen/logrus"
"net/http"
"strconv"
)
type Gateway interface {
Product(id string) (*model.Product, error)
}
type gateway struct {
client *retryablehttp.Client
host string
}
func NewGateway(c *retryablehttp.Client, host string) Gateway {
return gateway{client: c, host: host}
}
func (g gateway) Product(id string) (*model.Product, error) {
url := g.host + fmt.Sprintf("/products/%s", id)
req, err := retryablehttp.NewRequest("GET", url, nil)
if err != nil {
logrus.Errorln("Failed to create new request", err)
return nil, err
}
res, err := g.client.Do(req)
if err != nil {
logrus.Errorln("Failed to Do request", err)
return nil, err
}
if res.StatusCode != http.StatusOK {
logrus.Errorln(ErrorNotOk, strconv.Itoa(res.StatusCode))
return nil, ErrorNotOk
}
var p *Product
err = json.NewDecoder(res.Body).Decode(&p)
if err != nil {
logrus.Errorln("Failed to Decode", err)
return nil, err
}
defer res.Body.Close()
return g.mapProductToDomainProduct(p), nil
}