github.com/grafana/synthetic-monitoring-agent@v0.64.2/internal/secrets/gsm_client.go (about)

     1  package secrets
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  
     8  	gsmClient "github.com/grafana/gsm-api-go-client"
     9  )
    10  
    11  // GSMClientFactory creates GSM clients with proper configuration
    12  type GSMClientFactory struct{}
    13  
    14  // NewGSMClientFactory creates a new GSM client factory
    15  func NewGSMClientFactory() *GSMClientFactory {
    16  	return &GSMClientFactory{}
    17  }
    18  
    19  // CreateClient creates a new GSM client with the provided URL and token
    20  func (f *GSMClientFactory) CreateClient(url, token string) (gsmClient.ClientWithResponsesInterface, error) {
    21  	if url == "" {
    22  		return nil, fmt.Errorf("GSM URL cannot be empty")
    23  	}
    24  
    25  	if token == "" {
    26  		return nil, fmt.Errorf("GSM token cannot be empty")
    27  	}
    28  
    29  	return gsmClient.NewClientWithResponses(url, withAuth(token), withAcceptJSON())
    30  }
    31  
    32  // withAuth adds the Authorization header with Bearer token
    33  func withAuth(token string) gsmClient.ClientOption {
    34  	return gsmClient.WithRequestEditorFn(func(_ context.Context, req *http.Request) error {
    35  		req.Header.Add("Authorization", "Bearer "+token)
    36  		return nil
    37  	})
    38  }
    39  
    40  // withAcceptJSON adds the Accept: application/json header
    41  func withAcceptJSON() gsmClient.ClientOption {
    42  	return gsmClient.WithRequestEditorFn(func(_ context.Context, req *http.Request) error {
    43  		req.Header.Add("Accept", "application/json")
    44  		return nil
    45  	})
    46  }