/
agent.go
58 lines (49 loc) · 1.22 KB
/
agent.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
package engine
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/5sigma/conduit/postmaster/api"
"github.com/robertkrimen/otto"
"io/ioutil"
"net/http"
)
var (
Agents = make(map[string]string)
AgentAccessKey string
)
func _agent(call otto.FunctionCall) otto.Value {
agentName, _ := call.Argument(0).ToString()
fn, _ := call.Argument(1).ToString()
var address string
if a, ok := Agents[agentName]; ok {
address = a
} else {
jsThrow(call, errors.New("agent not found"))
}
req := &api.AgentRequest{
Function: fmt.Sprintf("(%s)();", fn),
}
req.Sign("", AgentAccessKey)
http.DefaultClient.Timeout = 0
requestBytes, err := json.Marshal(req)
url := fmt.Sprintf("http://%s", address)
reader := bytes.NewReader(requestBytes)
resp, err := http.Post(url, "application/json", reader)
if err != nil {
jsThrow(call, err)
}
responseData, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode == 404 {
jsThrow(call, errors.New("Agent not found"))
}
if resp.StatusCode != 200 {
var errorResponse api.ApiError
json.Unmarshal(responseData, &errorResponse)
jsThrow(call, errors.New(errorResponse.Error))
}
var response = api.AgentResponse{}
json.Unmarshal(responseData, &response)
return otto.Value{}
}