-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_writer.go
80 lines (66 loc) · 1.82 KB
/
http_writer.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
package main
import (
"fmt"
"bytes"
"time"
"math"
"net/http"
"net/url"
"encoding/json"
)
type HttpWriter struct {
Host,
Method string
ForceUseId bool `json:",omitempty"`
IntMultiFactor int
}
func (hw *HttpWriter) Send(slaves []*OwSlave) error {
var req *http.Request
var err error
switch hw.Method {
case http.MethodGet:
url, err := url.Parse(hw.Host)
if err != nil {
return fmt.Errorf("HttpWriter Send parsing host url (%v) failed:\n%v", hw.Host, err)
}
if url.Scheme == "" {
url.Scheme = "http"
}
url.RawQuery = hw.getSlavesQuery(slaves).Encode()
req, err = http.NewRequest(hw.Method, url.String(), nil)
if err != nil {
return fmt.Errorf("HttpWriter Send NewRequest (%v) failed:\n%v", hw.Method, err)
}
case http.MethodPost:
json, err := json.Marshal(slaves)
if err != nil {
return fmt.Errorf("HttpWriter Send json Marshal failed:\n%v", err)
}
req, err = http.NewRequest(hw.Method, hw.Host, bytes.NewReader(json))
if err != nil {
return fmt.Errorf("HttpWriter Send NewRequest (%v) failed:\n%v", hw.Method, err)
}
default:
return fmt.Errorf("HttpWriter Send: missing or unsupported http method\n")
}
req.Header.Set("Content-Type", "application/json")
client := http.Client{
Timeout: 6 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("HttpWriter Send http Client failed:\n%v", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 || resp.StatusCode < 200 {
return fmt.Errorf("HttpWriter Send error:\nReceived non-success http response from grenton host:\n%v", resp.Status)
}
return nil
}
func (hw *HttpWriter) getSlavesQuery(slaves []*OwSlave) (query url.Values) {
query = url.Values{}
for _, slv := range slaves {
query.Add(slv.Name, fmt.Sprintf("%.0f", math.Round(slv.Value * math.Pow10(hw.IntMultiFactor))))
}
return
}