-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbabashka.go
88 lines (71 loc) · 1.83 KB
/
babashka.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
package babashka
import (
"bufio"
"encoding/json"
"github.com/jackpal/bencode-go"
"log"
"os"
)
type Message struct {
Op string
Id string
Args string
Var string
}
type Namespace struct {
Name string "name"
Vars []Var "vars"
}
type Var struct {
Name string "name"
Code string `bencode:"code,omitempty"`
}
type DescribeResponse struct {
Format string "format"
Namespaces []Namespace "namespaces"
}
type InvokeResponse struct {
Id string "id"
Value string "value" // stringified json response
Status []string "status"
}
type ErrorResponse struct {
Id string "id"
Status []string "status"
ExMessage string "ex-message"
ExData string "ex-data"
}
func ReadMessage() *Message {
reader := bufio.NewReader(os.Stdin)
message := &Message{}
err := bencode.Unmarshal(reader, &message)
if err != nil {
log.Fatalln("Could not decode bencode message", err)
}
log.Printf("Received Message: %+v\n", message)
return message
}
func WriteDescribeResponse(describeResponse *DescribeResponse) {
writeResponse(*describeResponse)
}
func WriteInvokeResponse(inputMessage *Message, value interface{}) {
resultValue, err := json.Marshal(value)
if err != nil {
log.Fatalln("Could not marshall value to json", err)
}
response := InvokeResponse{Id: inputMessage.Id, Status: []string{"done"}, Value: string(resultValue)}
writeResponse(response)
}
func WriteErrorResponse(inputMessage *Message, err error) {
errorResponse := ErrorResponse{Id: inputMessage.Id, Status: []string{"done", "error"}, ExMessage: err.Error()}
writeResponse(errorResponse)
}
func writeResponse(response interface{}) {
log.Printf("Writing response: %+v\n", response)
writer := bufio.NewWriter(os.Stdout)
err := bencode.Marshal(writer, response)
if err != nil {
log.Fatalln("Couldn't write response", err)
}
writer.Flush()
}