ente/internal/api/client.go

72 lines
1.3 KiB
Go
Raw Normal View History

2023-09-07 03:23:25 +00:00
package api
import (
"errors"
"github.com/go-resty/resty/v2"
)
2023-09-08 14:42:58 +00:00
const (
2023-09-13 08:49:56 +00:00
EnteAPIEndpoint = "https://api.ente.io"
TokenHeader = "X-Auth-Token"
TokenQuery = "token"
2023-09-08 14:42:58 +00:00
)
var (
RedactedHeaders = []string{TokenHeader, " X-Request-Id"}
)
2023-09-07 03:23:25 +00:00
type Client struct {
restClient *resty.Client
2023-09-08 14:42:58 +00:00
authToken *string
}
type Params struct {
Debug bool
Trace bool
2023-09-13 08:49:56 +00:00
Host string
2023-09-07 03:23:25 +00:00
}
2023-09-08 14:42:58 +00:00
func NewClient(p Params) *Client {
2023-09-07 03:23:25 +00:00
c := resty.New()
2023-09-08 14:42:58 +00:00
if p.Trace {
c.EnableTrace()
}
if p.Debug {
c.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error {
logRequest(req)
return nil
})
c.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error {
logResponse(resp)
return nil
})
}
2023-09-07 03:23:25 +00:00
c.SetError(&Error{})
2023-09-13 08:49:56 +00:00
if p.Host != "" {
c.SetBaseURL(p.Host)
} else {
c.SetBaseURL(EnteAPIEndpoint)
}
2023-09-07 03:23:25 +00:00
return &Client{
restClient: c,
}
}
// Error type for resty.Error{}
type Error struct{}
// Implement Error() method for the error interface
func (e *Error) Error() string {
return "Error: response status code is not in the 2xx range"
}
// OnAfterResponse Implement OnAfterResponse() method for the resty.Error interface
func (e *Error) OnAfterResponse(resp *resty.Response) error {
if resp.StatusCode() < 200 || resp.StatusCode() >= 300 {
return errors.New(e.Error())
}
return nil
}