-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathusage.go
57 lines (46 loc) · 1.24 KB
/
usage.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
package run
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)
const (
// usageAPIBaseURL is the base URL for GCP project API, and
// the parameter is project NUMBER (not ID).
usageAPIBaseURL = "https://serviceusage.googleapis.com/v1/projects/%s/services?filter=state:ENABLED"
cloudRunAPI = "run.googleapis.com"
)
type usageServiceList struct {
Services []struct {
Config struct {
Name string `json:"name"`
} `json:"config"`
} `json:"services"`
}
func isAPIEnabled(ctx context.Context, projectNumber, uri string) (bool, error) {
if projectNumber == "" {
return false, errors.New("project number is empty")
}
u := fmt.Sprintf(usageAPIBaseURL, projectNumber)
req, err := http.NewRequest(http.MethodGet, u, nil)
if err != nil {
return false, errors.Wrap(err, "error client creating request")
}
var list usageServiceList
if err := apiClient.Get(ctx, req, &list); err != nil {
return false, errors.Wrap(err, "error decoding response")
}
log.Debug().Msgf("found %d services", len(list.Services))
if len(list.Services) == 0 {
return false, nil
}
for _, s := range list.Services {
if strings.EqualFold(s.Config.Name, uri) {
return true, nil
}
}
return false, nil
}