Skip to content

Commit

Permalink
first pass
Browse files Browse the repository at this point in the history
  • Loading branch information
dmarticus committed Oct 18, 2024
1 parent b26aef8 commit c802aec
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions posthog.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,29 @@ type client struct {
lastEventMutex sync.RWMutex
}

func (c *client) validateAPIKey() error {
url := c.Endpoint + "/decide/?v=3"
req, err := http.NewRequest("POST", url, nil)
if err != nil {
return fmt.Errorf("error creating request: %v", err)
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.key)

resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("invalid API key: received status code %d", resp.StatusCode)
}

return nil
}

// Instantiate a new client that uses the write key passed as first argument to
// send messages to the backend.
// The client is created with the default configuration.
Expand Down Expand Up @@ -125,6 +148,11 @@ func NewWithConfig(apiKey string, config Config) (cli Client, err error) {
}

if len(c.PersonalApiKey) > 0 {

if err := c.validateAPIKey(); err != nil {
return nil, fmt.Errorf("failed to initialize client: %v", err)
}

c.featureFlagsPoller = newFeatureFlagsPoller(
c.key,
c.Config.PersonalApiKey,
Expand Down Expand Up @@ -181,6 +209,10 @@ func dereferenceMessage(msg Message) Message {
}

func (c *client) Enqueue(msg Message) (err error) {
if c.key == "" {
return errors.New("client not properly initialized: invalid API key")
}

msg = dereferenceMessage(msg)
if err = msg.Validate(); err != nil {
return
Expand Down

0 comments on commit c802aec

Please sign in to comment.