104 lines
1.9 KiB
Go
104 lines
1.9 KiB
Go
package pangolin
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/auroradevllc/apiclient"
|
|
)
|
|
|
|
func New(apiUrl, apiKey string) *Client {
|
|
return &Client{
|
|
apiUrl: apiUrl,
|
|
apiKey: apiKey,
|
|
}
|
|
}
|
|
|
|
type Client struct {
|
|
apiUrl string
|
|
apiKey string
|
|
debug bool
|
|
}
|
|
|
|
type Response[V any] struct {
|
|
Success bool `json:"success"`
|
|
Error bool `json:"error"`
|
|
Message string `json:"message"`
|
|
Pagination struct {
|
|
Total int `json:"total"`
|
|
PageSize int `json:"pageSize"`
|
|
Page int `json:"page"`
|
|
}
|
|
Data V `json:"data"`
|
|
}
|
|
|
|
func (p *Client) Domains(orgID string) ([]Domain, error) {
|
|
var response Response[DomainResponse]
|
|
|
|
if err := p.doRequestJSON(http.MethodGet, "/org/"+orgID+"/domains", nil, &response); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return response.Data.Domains, nil
|
|
}
|
|
|
|
func (p *Client) Resources(orgID string) ([]Resource, error) {
|
|
var response Response[ResourceResponse]
|
|
|
|
if err := p.doRequestJSON(http.MethodGet, "/org/"+orgID+"/resources?pageSize=1000", nil, &response); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return response.Data.Resources, nil
|
|
}
|
|
|
|
func (p *Client) doRequest(method, uri string, body any) (*apiclient.Response, error) {
|
|
opts := []apiclient.Option{
|
|
apiclient.WithMethod(method),
|
|
apiclient.WithHeader("Authorization", "Bearer "+p.apiKey),
|
|
}
|
|
|
|
if body != nil {
|
|
opts = append(opts, apiclient.WithJSON(body))
|
|
}
|
|
|
|
req, err := apiclient.NewRequest(p.apiUrl+"/"+strings.TrimLeft(uri, "/"), opts...)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
res, err := req.Send()
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return res, nil
|
|
}
|
|
|
|
func (p *Client) doRequestJSON(method, uri string, body any, out any) error {
|
|
res, err := p.doRequest(method, uri, body)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// If debugging, we want to read the entire body
|
|
if p.debug {
|
|
b, err := res.Bytes()
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Println(string(b))
|
|
|
|
return json.Unmarshal(b, out)
|
|
}
|
|
|
|
return res.Unmarshal(out)
|
|
}
|