-
Notifications
You must be signed in to change notification settings - Fork 230
/
bits.go
68 lines (57 loc) · 1.55 KB
/
bits.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
package bits
import (
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"github.com/cockroachdb/errors"
)
type Bit struct {
Slug string
Title string
Description string
// GitHubTree is a URL to the GitHub tree for this bit,
// in the format expected by github.ParseTree.
GitHubTree string
}
// List lists available bits.
func List(ctx context.Context) ([]*Bit, error) {
resp, err := http.Get("https://automativity.encore.dev/bits")
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
slurp, _ := io.ReadAll(resp.Body)
return nil, errors.Newf("got status %d: %s", resp.StatusCode, slurp)
}
var data struct {
Bits []*Bit
}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return nil, errors.Wrap(err, "decode json response")
}
return data.Bits, nil
}
// ErrNotFound is reported by Get if the bit with the given slug is not found.
var ErrNotFound = errors.New("bit not found")
// Get retrieves a bit by its slug.
func Get(ctx context.Context, slug string) (*Bit, error) {
resp, err := http.Get("https://automativity.encore.dev/bits/" + url.PathEscape(slug))
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == 404 {
return nil, ErrNotFound
} else if resp.StatusCode != 200 {
slurp, _ := io.ReadAll(resp.Body)
return nil, errors.Newf("got status %d: %s", resp.StatusCode, slurp)
}
var bit Bit
if err := json.NewDecoder(resp.Body).Decode(&bit); err != nil {
return nil, errors.Wrap(err, "decode json response")
}
return &bit, nil
}