Skip to content

Commit

Permalink
feat: allow to skip the initial token check
Browse files Browse the repository at this point in the history
  • Loading branch information
johanneswuerbach committed Apr 24, 2024
1 parent e35a4e2 commit 4ac2bdb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
25 changes: 20 additions & 5 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,29 @@ const (
)

var (
SDKHeader = fmt.Sprintf("%s/%s", SDK, SDKVersion)
SDKHeader = fmt.Sprintf("%s/%s", SDK, SDKVersion)
ErrMissingToken = errors.New("token is required")
)

type Config struct {
// Token used for API requests
Token string
URL string

InternalApp string
// URL is the base URL for the API requests (optional)
URL string

// Callbacks for logging requests and responses (optional)
RequestLogger func(r *RequestDetails)
ResponseLogger func(r *ResponseDetails)
Client client.HttpRequestDoer

// Use a custom HTTP client (optional)
Client client.HttpRequestDoer

// Skip initial token check (optional)
SkipInitialTokenCheck bool

// Internal usage tracking (optional)
InternalApp string
}

type RequestDetails struct {
Expand All @@ -57,7 +68,7 @@ func (c *Client) Client() *client.Client {
}

func NewClient(config *Config) (*Client, error) {
if config.Token == "" {
if config.Token == "" && !config.SkipInitialTokenCheck {
return nil, ErrMissingToken
}

Expand All @@ -75,6 +86,10 @@ func NewClient(config *Config) (*Client, error) {
baseClient, err := client.NewClient(config.URL, func(c *client.Client) error {
c.Client = &DoWithLog{doer, config.RequestLogger, config.ResponseLogger}
c.RequestEditors = append(c.RequestEditors, func(_ context.Context, req *http.Request) error {
if config.Token == "" {
return ErrMissingToken
}

req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.Token))
req.Header.Add("Humanitec-User-Agent", humanitecUserAgent(config.InternalApp, SDKHeader))
return nil
Expand Down
15 changes: 15 additions & 0 deletions api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,18 @@ func TestNewHumanitecClientMissingToken(t *testing.T) {
})
assert.ErrorIs(err, ErrMissingToken)
}

func TestNewHumanitecClientMissingTokenSkipCheck(t *testing.T) {
assert := assert.New(t)

srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Fail("Shouldn't be called")
}))
defer srv.Close()

_, err := NewClient(&Config{
URL: srv.URL,
SkipInitialTokenCheck: true,
})
assert.NoError(err)
}

0 comments on commit 4ac2bdb

Please sign in to comment.