feat(publicip/ipinfo): add PUBLICIP_API_TOKEN variable

This commit is contained in:
Quentin McGaw
2024-02-13 10:55:06 +00:00
parent 72b5afc771
commit 6a6337b98f
6 changed files with 29 additions and 4 deletions

View File

@@ -14,15 +14,18 @@ import (
type Fetch struct {
client *http.Client
token string
}
func New(client *http.Client) *Fetch {
func New(client *http.Client, token string) *Fetch {
return &Fetch{
client: client,
token: token,
}
}
var (
ErrTokenNotValid = errors.New("token is not valid")
ErrTooManyRequests = errors.New("too many requests sent for this month")
ErrBadHTTPStatus = errors.New("bad HTTP status received")
)
@@ -44,6 +47,7 @@ func (f *Fetch) FetchInfo(ctx context.Context, ip netip.Addr) (
if err != nil {
return result, err
}
request.Header.Set("Authorization", "Bearer "+f.token)
response, err := f.client.Do(request)
if err != nil {
@@ -51,6 +55,10 @@ func (f *Fetch) FetchInfo(ctx context.Context, ip netip.Addr) (
}
defer response.Body.Close()
if f.token != "" && response.StatusCode == http.StatusUnauthorized {
return result, fmt.Errorf("%w: %s", ErrTokenNotValid, response.Status)
}
switch response.StatusCode {
case http.StatusOK:
case http.StatusTooManyRequests, http.StatusForbidden: