Files
email-api-client/client/client.go
Ron Rise 95bb27698b
All checks were successful
🚀 Publish Release Package / publish (push) Successful in 21s
refactor: enhance error handling in client creation and context management
2025-06-25 12:30:29 -04:00

65 lines
1.2 KiB
Go
Executable File

package client
import (
"context"
"errors"
)
type Client struct {
config *Configuration
token *Token
}
type contextKeyType string
var contextKey contextKeyType = "client"
type accessTokenRequest struct {
GrantType string `json:"grant_type"`
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
}
func NewClient(config *Configuration) (*Client, error) {
client := &Client{
config: config,
}
token, err := getToken(client.config)
if err != nil {
return nil, errors.New("failed to get token: " + err.Error())
}
client.token = token
return client, nil
}
func FromContext(ctx context.Context) *Client {
client := ctx.Value(contextKey)
if client == nil {
return nil
}
if c, ok := client.(*Client); ok {
return c
}
return nil
}
func NewWithContext(ctx context.Context, config *Configuration) (context.Context, error) {
client, err := NewClient(config)
if err != nil {
return nil, errors.New("failed to create client: " + err.Error())
}
ctx = context.WithValue(ctx, contextKey, client)
if c, ok := ctx.Value(contextKey).(*Client); ok {
return context.WithValue(ctx, contextKey, c), nil
} else {
return nil, errors.New("failed to set client in context")
}
}