-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplay.go
74 lines (61 loc) · 1.94 KB
/
play.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
package play
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"time"
"golang.org/x/sync/errgroup"
)
// Client represents an HTTP and Config instance combo used to make calls to the
// Go Playground.
type Client struct {
http http.Client // An HTTP client used to dispatch requests to the Go Playground
config Config // A configuration object used to compose Go Playground URLs
}
// NewClient returns a new instance of struct Client using the specified Config
// instance.
func NewClient(config Config) Client {
client := http.Client{
Timeout: 60 * time.Second,
}
return Client{
http: client,
config: config,
}
}
// FetchGroup takes a slice of byte slices representing multiple snippets of
// Go source code to process. This method makes use of the `errgroup` package
// which utilises Goroutines to process multiple snippets concurrently. This
// method stops on the first non-nil error response. The order of resulting
// slice of strings is not guaranteed.
func (c Client) FetchGroup(sources [][]byte) (result []string, err error) {
errors := new(errgroup.Group)
for _, source := range sources {
source := source // shadow here as we cannot pass as parameter to error group func
errors.Go(func() error {
url, err := c.Fetch(source)
if err != nil {
return err
}
result = append(result, url)
return nil
})
}
if err := errors.Wait(); err != nil {
return result, err
}
return result, err
}
// Fetch takes a single slice of bytes representing a snippet of Go source code
// to process in the Go Playground. This method returns either an error or a
// shareable Go Playground URL.
func (c Client) Fetch(source []byte) (result string, err error) {
response, err := c.http.Post(c.config.GetPostUrl(), "raw", bytes.NewBuffer(source))
if err != nil {
return result, err
}
defer response.Body.Close()
code, _ := ioutil.ReadAll(response.Body)
return fmt.Sprintf("%s/%s", c.config.GetShareUrl(), string(code)), err
}