forked from nytlabs/st-core
/
IO.go
97 lines (78 loc) · 1.56 KB
/
IO.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
package core
import (
"encoding/json"
"io"
"net/http"
)
func Write() Spec {
return Spec{
Name: "write",
Inputs: []Pin{
Pin{"writer", WRITER},
Pin{"msg", ANY},
},
Outputs: []Pin{
Pin{"writer", WRITER},
},
Kernel: func(in, out, internal MessageMap, s Source, i chan Interrupt) Interrupt {
writer, ok := in[0].(io.Writer)
if !ok {
out[0] = NewError("writer must implement io.Writer")
return nil
}
data, err := json.Marshal(in[1])
if err != nil {
out[0] = NewError("could not marshal msg")
return nil
}
_, err = writer.Write(data)
if err != nil {
out[0] = NewError("could not write data to writer")
return nil
}
out[0] = writer
return nil
},
}
}
func Close() Spec {
return Spec{
Name: "close",
Inputs: []Pin{
Pin{"writer", WRITER},
},
Kernel: func(in, out, internal MessageMap, s Source, i chan Interrupt) Interrupt {
writer, ok := in[0].(io.Closer)
if !ok {
out[0] = NewError("writer must implement io.Writer")
return nil
}
err := writer.Close()
if err != nil {
out[0] = NewError("could not close writer")
}
return nil
},
}
}
func Flush() Spec {
return Spec{
Name: "flush",
Inputs: []Pin{
Pin{"writer", WRITER},
},
Outputs: []Pin{
Pin{"writer", WRITER},
},
Kernel: func(in, out, internal MessageMap, s Source, i chan Interrupt) Interrupt {
writer, ok := in[0].(http.Flusher)
if !ok {
out[0] = NewError("writer must implement http.Flusher")
return nil
}
writer.Flush()
out[0] = writer
return nil
},
}
}