-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathndjson_execution.go
More file actions
88 lines (66 loc) · 1.55 KB
/
ndjson_execution.go
File metadata and controls
88 lines (66 loc) · 1.55 KB
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 gowandbox
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
)
// Returns new GWBProgram struct
func NewGWBNDProgram() *GWBNDProgram {
return &GWBNDProgram{}
}
/*
Method to read ndjson.
Returns a GWNDBMessage struct, which provides the type of the message, and data.
On reaching the end, an `io.EOF` error is returned.
*/
func (r *GWBNDReader) Next() (GWBNDMessage, error) {
if !r.source.Scan() {
return GWBNDMessage{}, io.EOF
}
data := []byte(r.source.Text())
if err := r.source.Err(); err != nil {
return GWBNDMessage{}, err
}
result := GWBNDMessage{}
err := json.Unmarshal(data, &result)
return result, err
}
/*
Method to execute a GWBProgram
If no errors ocurred, the result is returned in the form of a GWBNDReader struct.
If the response code is not 200, an error is returned.
Maps to the `/compile.ndjson` endpoint
*/
func (g *GWBNDProgram) Execute(ctx context.Context) (GWBNDReader, error) {
data, err := json.Marshal(g)
var result GWBNDReader
if err != nil {
return result, err
}
client := http.DefaultClient
req, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
WandBoxUrl+"compile.ndjson",
bytes.NewBuffer(data),
)
if err != nil {
return result, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return result, err
}
if resp.StatusCode != http.StatusOK {
e, _ := ioutil.ReadAll(resp.Body)
return result, errors.New(string(e))
}
result.source = bufio.NewScanner(resp.Body)
return result, err
}