|
| 1 | +package clients |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "net/http" |
| 7 | + "net/url" |
| 8 | + |
| 9 | + "distributed-db/models" |
| 10 | +) |
| 11 | + |
| 12 | +func NewHTTP(host string) *HTTPClient { |
| 13 | + client := HTTPClient{ |
| 14 | + host: host, |
| 15 | + httpClient: &http.Client{}, |
| 16 | + } |
| 17 | + return &client |
| 18 | +} |
| 19 | + |
| 20 | +type HTTPClient struct { |
| 21 | + host string |
| 22 | + httpClient *http.Client |
| 23 | +} |
| 24 | + |
| 25 | +func (c *HTTPClient) Get(peer string, key string) (models.CacheItem, error) { |
| 26 | + body := models.GetRequest{ |
| 27 | + Keys: []string{key}, |
| 28 | + } |
| 29 | + req, err := c.makeRequest(http.MethodGet, c.url(peer, "get"), body) |
| 30 | + if err != nil { |
| 31 | + return models.CacheItem{}, err |
| 32 | + } |
| 33 | + |
| 34 | + res, err := c.httpClient.Do(req) |
| 35 | + if err != nil { |
| 36 | + return models.CacheItem{}, err |
| 37 | + } |
| 38 | + |
| 39 | + var cacheItem []models.CacheItem |
| 40 | + err = json.NewDecoder(res.Body).Decode(&cacheItem) |
| 41 | + if err != nil { |
| 42 | + return models.CacheItem{}, err |
| 43 | + } |
| 44 | + |
| 45 | + return cacheItem[0], nil |
| 46 | +} |
| 47 | + |
| 48 | +func (c *HTTPClient) Gossip(peer string, summary models.Summary) error { |
| 49 | + body := models.GossipRequest{ |
| 50 | + Summary: summary, |
| 51 | + } |
| 52 | + req, err := c.makeRequest(http.MethodPost, c.url(peer, "gossip"), body) |
| 53 | + if err != nil { |
| 54 | + return err |
| 55 | + } |
| 56 | + |
| 57 | + _, err = c.httpClient.Do(req) |
| 58 | + if err != nil { |
| 59 | + return err |
| 60 | + } |
| 61 | + |
| 62 | + return nil |
| 63 | +} |
| 64 | + |
| 65 | +func (c *HTTPClient) url(peer, path string) string { |
| 66 | + u := url.URL{ |
| 67 | + Scheme: "http", |
| 68 | + Host: peer, |
| 69 | + Path: path, |
| 70 | + } |
| 71 | + return u.String() |
| 72 | +} |
| 73 | + |
| 74 | +func (c *HTTPClient) makeRequest(method, url string, body interface{}) (*http.Request, error) { |
| 75 | + bs, err := json.Marshal(body) |
| 76 | + if err != nil { |
| 77 | + return nil, err |
| 78 | + } |
| 79 | + |
| 80 | + req, err := http.NewRequest(method, url, bytes.NewReader(bs)) |
| 81 | + if err != nil { |
| 82 | + return nil, err |
| 83 | + } |
| 84 | + req.Host = c.host |
| 85 | + |
| 86 | + return req, nil |
| 87 | +} |
0 commit comments