github.com/pluralsh/plural-cli@v0.9.5/pkg/exp/posthog/client.go (about)

     1  package posthog
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"net/http"
     8  	"time"
     9  
    10  	"github.com/posthog/posthog-go"
    11  )
    12  
    13  const (
    14  	publicAPIKey = "phc_r0v4jbKz8Rr27mfqgO15AN5BMuuvnU8hCFedd6zpSDy"
    15  	endpoint     = "posthog.plural.sh"
    16  )
    17  
    18  type posthogClient struct {
    19  	config      Config
    20  	contentType string
    21  	client      http.Client
    22  }
    23  
    24  func (this *posthogClient) IsFeatureEnabled(payload FeatureFlagPayload) (bool, error) {
    25  	values := posthog.DecideRequestData{
    26  		ApiKey:     this.config.APIKey,
    27  		DistinctId: payload.DistinctId,
    28  		PersonProperties: posthog.Properties{
    29  			"email": payload.DistinctId,
    30  		},
    31  	}
    32  	data, err := json.Marshal(values)
    33  	if err != nil {
    34  		return false, err
    35  	}
    36  
    37  	resp, err := this.client.Post(this.decideEndpoint(), this.contentType, bytes.NewBuffer(data))
    38  	if err != nil {
    39  		return false, err
    40  	}
    41  
    42  	defer resp.Body.Close()
    43  
    44  	decide := new(posthog.DecideResponse)
    45  	err = json.NewDecoder(resp.Body).Decode(decide)
    46  	if err != nil {
    47  		return false, err
    48  	}
    49  
    50  	enabled := decide.FeatureFlags[payload.Key]
    51  
    52  	switch v := enabled.(type) {
    53  	case nil:
    54  		return false, nil
    55  	case bool:
    56  		return v, nil
    57  	case string:
    58  		return v == "true", nil
    59  	default:
    60  		return true, nil
    61  	}
    62  }
    63  
    64  func (this *posthogClient) decideEndpoint() string {
    65  	return fmt.Sprintf("https://%s/decide/?v=3", this.config.Endpoint)
    66  }
    67  
    68  func New() Client {
    69  	return &posthogClient{
    70  		config: Config{
    71  			APIKey:   publicAPIKey,
    72  			Endpoint: endpoint,
    73  		},
    74  		contentType: "application/json",
    75  		client: http.Client{
    76  			Timeout: 5 * time.Second,
    77  		},
    78  	}
    79  }