-
Notifications
You must be signed in to change notification settings - Fork 4
/
source_backstage.go
78 lines (65 loc) · 1.86 KB
/
source_backstage.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
package source
import (
"context"
"encoding/json"
"fmt"
"net/http"
kitlog "github.com/go-kit/kit/log"
"github.com/go-ozzo/ozzo-validation/is"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/hashicorp/go-cleanhttp"
"github.com/pkg/errors"
)
type SourceBackstage struct {
Endpoint string `json:"endpoint"` // https://backstage.company.io/api/catalog/entities
Token Credential `json:"token"`
}
func (s SourceBackstage) Validate() error {
return validation.ValidateStruct(&s,
validation.Field(&s.Endpoint,
validation.Required.Error("must provide an endpoint for fetching Backstage entries"),
is.URL,
),
)
}
func (s SourceBackstage) String() string {
return fmt.Sprintf("backstage (endpoint=%s)", s.Endpoint)
}
func (s SourceBackstage) Load(ctx context.Context, logger kitlog.Logger) ([]*SourceEntry, error) {
client := cleanhttp.DefaultClient()
var (
limit = 100
offset = 0
)
entries := []*SourceEntry{}
for {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.Endpoint+fmt.Sprintf("?limit=%d&offset=%d", limit, offset), nil)
if err != nil {
return nil, errors.Wrap(err, "building Backstage URL")
}
if string(s.Token) != "" {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", string(s.Token)))
}
resp, err := client.Do(req)
if err == nil && resp.StatusCode != http.StatusOK {
err = fmt.Errorf("received error from Backstage: %s", resp.Status)
}
if err != nil {
return nil, errors.Wrap(err, "fetching Backstage entries")
}
page := []json.RawMessage{}
if err := json.NewDecoder(resp.Body).Decode(&page); err != nil {
return nil, errors.Wrap(err, "parsing Backstage entries")
}
if len(page) == 0 {
return entries, nil
}
for idx := range page {
entries = append(entries, &SourceEntry{
Origin: s.String(),
Content: page[idx],
})
}
offset += len(page)
}
}