You've already forked email-api-client
All checks were successful
🚀 Publish Release Package / publish (push) Successful in 23s
67 lines
1.6 KiB
Go
Executable File
67 lines
1.6 KiB
Go
Executable File
package client
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type EmailCreateResponse struct {
|
|
Id string `json:"id"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
LimitRemaining int `json:"limit_remaining,omitempty"`
|
|
}
|
|
|
|
type ErrorResponse struct {
|
|
Message string `json:"message"`
|
|
Error string `json:"error"`
|
|
}
|
|
|
|
func (client *Client) SendEmail(request *EmailRequest) (*EmailCreateResponse, error) {
|
|
jsonData, _ := json.Marshal(request)
|
|
|
|
httpClient := &http.Client{}
|
|
req, _ := http.NewRequest(
|
|
"POST",
|
|
client.config.Endpoint+"/api/email",
|
|
bytes.NewReader(jsonData),
|
|
)
|
|
req.Header.Set("Authorization", client.token.TokenType+" "+client.token.AccessToken)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := httpClient.Do(req)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if resp.StatusCode >= http.StatusBadRequest {
|
|
response, err := readResponseBody[Response[ErrorResponse]](resp)
|
|
if err != nil {
|
|
bodyContents := make([]byte, resp.ContentLength)
|
|
_, err := resp.Body.Read(bodyContents)
|
|
|
|
if err != nil {
|
|
return nil, errors.New("Failed to read error response body: " + err.Error())
|
|
}
|
|
|
|
return nil, errors.New("An error occurred while sending the email: " + resp.Status + " - " + string(bodyContents))
|
|
}
|
|
|
|
if response.Payload.Message == "" {
|
|
response.Payload.Message = "An error occurred while sending the email: " + resp.Status
|
|
}
|
|
|
|
return nil, errors.New("" + response.Payload.Message + " (Error: " + response.Payload.Error + ")")
|
|
}
|
|
|
|
response, err := readResponseBody[Response[EmailCreateResponse]](resp)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &response.Payload, nil
|
|
}
|