-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
64 lines (56 loc) · 1.09 KB
/
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
package main
import (
"bytes"
"encoding/binary"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"os"
)
func init() {
log.SetFlags(0)
log.SetOutput(os.Stderr)
flag.Parse()
}
func main() {
dec := json.NewDecoder(os.Stdin)
for {
var msg interface{}
if err := dec.Decode(&msg); err != nil {
if err == io.EOF {
break
}
log.Fatalf("read message: %v", err)
}
if err := writeMessage(msg, os.Stdout); err != nil {
log.Printf("write message: %v", err)
}
}
}
func writeMessage(msg interface{}, w io.Writer) error {
jsonBytes, err := json.Marshal(msg)
if err != nil {
return err
}
if err := writeMessageLength(jsonBytes, w); err != nil {
return err
}
var buf bytes.Buffer
n, err := buf.Write(jsonBytes)
if err != nil {
return err
}
if n != len(jsonBytes) {
return fmt.Errorf("message not fully written")
}
nWritten, err := buf.WriteTo(w)
if nWritten != int64(len(jsonBytes)) {
return fmt.Errorf("message not fully written")
}
return err
}
func writeMessageLength(msg []byte, w io.Writer) error {
return binary.Write(w, binary.LittleEndian, uint32(len(msg)))
}