forked from kazuhitoyokoi/node-red-wasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
red.go
98 lines (92 loc) · 2.58 KB
/
red.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//go:build js && wasm
// +build js,wasm
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"strconv"
"syscall/js" // wasm
"time"
)
type handler struct{}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "testtest")
}
func execute(nodeId string, msg string) {
var flowJson = []byte(flows())
var flowItems []map[string]interface{}
json.Unmarshal(flowJson, &flowItems)
for i := 0; i < len(flowItems); i++ {
var nodeType = flowItems[i]["type"]
var currentNodeId = flowItems[i]["id"]
var nodeWires = flowItems[i]["wires"].([]interface{})
if nodeType == "inject" && nodeId == "" {
var repeat = flowItems[i]["repeat"].(string)
go func() {
if repeat == "" {
var t = time.Now()
var msg2 = `{"payload":` + strconv.FormatInt(t.UnixMilli(), 10) + "}"
for j := 0; j < len(nodeWires); j++ {
var nodeWire = nodeWires[j].([]interface{})
execute(nodeWire[0].(string), msg2)
}
} else {
i, _ = strconv.Atoi(repeat)
ticker := time.NewTicker(time.Duration(i) * time.Second)
defer ticker.Stop()
done := make(chan bool)
go func() {
time.Sleep(24 * time.Hour)
done <- true
}()
for {
select {
case <-done:
return
case t := <-ticker.C:
var msg2 = `{"payload":` + strconv.FormatInt(t.UnixMilli(), 10) + "}"
for j := 0; j < len(nodeWires); j++ {
var nodeWire = nodeWires[j].([]interface{})
execute(nodeWire[0].(string), msg2)
}
}
}
}
}()
} else if nodeType == "debug" && nodeId == currentNodeId {
var msgData interface{}
json.Unmarshal([]byte(msg), &msgData)
var output = msgData.(map[string]interface{})["payload"]
var text = ""
var kind = reflect.TypeOf(output).Kind()
if kind == reflect.Float64 {
text = strconv.FormatFloat(output.(float64), 'f', -1, 64)
} else if kind == reflect.Map || kind == reflect.Slice {
jsonData, _ := json.Marshal(output)
text = string(jsonData)
} else {
text = output.(string)
}
fmt.Println(text)
js.Global().Get("debug").Invoke(text) // wasm
} else if nodeType == "http request" && nodeId == currentNodeId {
var url = flowItems[i]["url"]
resp, _ := http.Get(url.(string))
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var msg2 = `{"payload":` + string(body) + "}"
for j := 0; j < len(nodeWires); j++ {
var nodeWire = nodeWires[j].([]interface{})
execute(nodeWire[0].(string), msg2)
}
}
}
}
func main() {
execute("", "{}")
http.Handle("/", new(handler))
http.ListenAndServe(":1880", nil)
}