You've already forked email-api-client
refactor: enhance error handling in client creation and context management
All checks were successful
🚀 Publish Release Package / publish (push) Successful in 21s
All checks were successful
🚀 Publish Release Package / publish (push) Successful in 21s
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
package client
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
config *Configuration
|
||||
@@ -17,7 +20,7 @@ type accessTokenRequest struct {
|
||||
ClientSecret string `json:"client_secret"`
|
||||
}
|
||||
|
||||
func NewClient(config *Configuration) *Client {
|
||||
func NewClient(config *Configuration) (*Client, error) {
|
||||
|
||||
client := &Client{
|
||||
config: config,
|
||||
@@ -25,12 +28,12 @@ func NewClient(config *Configuration) *Client {
|
||||
|
||||
token, err := getToken(client.config)
|
||||
if err != nil {
|
||||
return nil
|
||||
return nil, errors.New("failed to get token: " + err.Error())
|
||||
}
|
||||
|
||||
client.token = token
|
||||
|
||||
return client
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func FromContext(ctx context.Context) *Client {
|
||||
@@ -46,15 +49,16 @@ func FromContext(ctx context.Context) *Client {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewWithContext(ctx context.Context) context.Context {
|
||||
client := ctx.Value(contextKey)
|
||||
if client == nil {
|
||||
return ctx
|
||||
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())
|
||||
}
|
||||
|
||||
if c, ok := client.(*Client); ok {
|
||||
return context.WithValue(ctx, contextKey, c)
|
||||
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")
|
||||
}
|
||||
|
||||
return ctx
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package client
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"gitea.siteworxpro.com/golang-packages/email-api-client/redis"
|
||||
"net/http"
|
||||
"time"
|
||||
@@ -47,6 +48,10 @@ func getToken(configuration *Configuration) (*Token, error) {
|
||||
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)
|
||||
_, err = resp.Body.Read(responseBody)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user