refactor: enhance error handling in client creation and context management
All checks were successful
🚀 Publish Release Package / publish (push) Successful in 21s

This commit is contained in:
2025-06-25 12:30:29 -04:00
parent ac789c1cba
commit 95bb27698b
2 changed files with 21 additions and 12 deletions

View File

@@ -1,6 +1,9 @@
package client package client
import "context" import (
"context"
"errors"
)
type Client struct { type Client struct {
config *Configuration config *Configuration
@@ -17,7 +20,7 @@ type accessTokenRequest struct {
ClientSecret string `json:"client_secret"` ClientSecret string `json:"client_secret"`
} }
func NewClient(config *Configuration) *Client { func NewClient(config *Configuration) (*Client, error) {
client := &Client{ client := &Client{
config: config, config: config,
@@ -25,12 +28,12 @@ func NewClient(config *Configuration) *Client {
token, err := getToken(client.config) token, err := getToken(client.config)
if err != nil { if err != nil {
return nil return nil, errors.New("failed to get token: " + err.Error())
} }
client.token = token client.token = token
return client return client, nil
} }
func FromContext(ctx context.Context) *Client { func FromContext(ctx context.Context) *Client {
@@ -46,15 +49,16 @@ func FromContext(ctx context.Context) *Client {
return nil return nil
} }
func NewWithContext(ctx context.Context) context.Context { func NewWithContext(ctx context.Context, config *Configuration) (context.Context, error) {
client := ctx.Value(contextKey) client, err := NewClient(config)
if client == nil { if err != nil {
return ctx return nil, errors.New("failed to create client: " + err.Error())
} }
if c, ok := client.(*Client); ok { ctx = context.WithValue(ctx, contextKey, client)
return context.WithValue(ctx, contextKey, c) 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")
} }
return ctx
} }

View File

@@ -3,6 +3,7 @@ package client
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"errors"
"gitea.siteworxpro.com/golang-packages/email-api-client/redis" "gitea.siteworxpro.com/golang-packages/email-api-client/redis"
"net/http" "net/http"
"time" "time"
@@ -47,6 +48,10 @@ func getToken(configuration *Configuration) (*Token, error) {
return nil, err return nil, err
} }
if resp.StatusCode != http.StatusOK || resp.ContentLength <= 0 {
return nil, errors.New("Failed to retrieve access token: " + resp.Status)
}
responseBody := make([]byte, resp.ContentLength) responseBody := make([]byte, resp.ContentLength)
_, err = resp.Body.Read(responseBody) _, err = resp.Body.Read(responseBody)
if err != nil { if err != nil {