forked from schollz/find3-cli-scanner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-main.go
76 lines (66 loc) · 1.42 KB
/
server-main.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
package main
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"time"
log "github.com/cihub/seelog"
"github.com/schollz/find3/server/main/src/models"
)
var (
httpClient *http.Client
)
const (
MaxIdleConnections int = 20
RequestTimeout int = 60
)
// init HTTPClient
func init() {
httpClient = createHTTPClient()
}
// createHTTPClient for connection re-use
func createHTTPClient() *http.Client {
client := &http.Client{
Transport: &http.Transport{
MaxIdleConnsPerHost: MaxIdleConnections,
},
Timeout: time.Duration(RequestTimeout) * time.Second,
}
return client
}
type Response struct {
Success bool `json:"success"`
Message string `json:"message"`
}
func postData(payload models.SensorData, route string) (err error) {
log.Debug("posting data")
if len(payload.Sensors) == 0 {
return errors.New("no sensor data")
}
if string(server[len(server)-1]) == "/" {
server = server[:len(server)-1]
}
url := server + route
bPayload, err := json.Marshal(payload)
if err != nil {
return
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(bPayload))
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
var target Response
err = json.NewDecoder(resp.Body).Decode(&target)
if err != nil {
return
}
if !target.Success {
err = errors.New("unable to analyze: " + target.Message)
}
log.Debug(target)
return
}