/
godbolt.go
82 lines (74 loc) · 1.78 KB
/
godbolt.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
package internal
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
type CompilerExplorerClientState struct {
Sessions []Sessions `json:"sessions"`
}
type Compilers struct {
ID string `json:"id"`
Options string `json:"options"`
}
type Compiler struct {
ID string `json:"id"`
Libs []interface{} `json:"libs"`
Options string `json:"options"`
}
type Executors struct {
Arguments string `json:"arguments"`
Compiler Compiler `json:"compiler"`
Stdin string `json:"stdin"`
}
type Sessions struct {
ID int `json:"id"`
Language string `json:"language"`
Source string `json:"source"`
Compilers []Compilers `json:"compilers"`
Executors []Executors `json:"executors"`
}
type Response struct {
URL string `json:"url"`
}
func OpenInCompilerExplorer(source string) (url string, err error) {
cs := CompilerExplorerClientState{
Sessions: []Sessions{
{
ID: 1,
Language: "go",
Source: source,
Compilers: []Compilers{
{ID: "gltip"},
},
Executors: []Executors{},
},
},
}
csj, err := json.Marshal(cs)
if err != nil {
return "", fmt.Errorf("marshal request: %w", err)
}
res, err := http.Post("https://godbolt.org/api/shortener", "application/json", bytes.NewBuffer(csj))
if err != nil {
return "", fmt.Errorf("post request: %w", err)
}
defer res.Body.Close()
defer io.Copy(io.Discard, res.Body)
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("unexpected response code: %d", res.StatusCode)
}
resb, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", fmt.Errorf("read response: %w", err)
}
resm := Response{}
err = json.Unmarshal(resb, &resm)
if err != nil {
return "", fmt.Errorf("unmarshal response: %w", err)
}
return resm.URL, nil
}