Mail api for sending order confirmation to planetposen customers

This commit is contained in:
2022-12-02 18:26:07 +01:00
commit 2812f6bcbf
13 changed files with 782 additions and 0 deletions

135
client/http.go Normal file
View File

@@ -0,0 +1,135 @@
// Package client contains a HTTP client.
package client
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
opentracing "github.com/opentracing/opentracing-go"
)
// Parameters provides the parameters used when creating a new HTTP client.
type Parameters struct {
Timeout *time.Duration
}
// NewHTTPClient instantiates a new HTTPClient based on provided parameters.
func NewHTTPClient(parameters Parameters) HTTPClient {
if parameters.Timeout == nil {
timeout := 1 * time.Second
parameters.Timeout = &timeout
}
client := &http.Client{
Timeout: *parameters.Timeout,
}
return HTTPClient{client}
}
// HTTPRequestData contains the request data.
type HTTPRequestData struct {
Method string
URL string
Headers map[string]string
PostPayload []byte
GetPayload *url.Values
}
// HTTPClient contains the HTTP client.
type HTTPClient struct {
*http.Client
}
// HTTPStatusCodeError is an error that occurs when receiving an unexpected status code (>= 400).
type HTTPStatusCodeError struct {
URL string
StatusCode int
Message string
}
// Error return an error string.
func (e HTTPStatusCodeError) Error() string {
return fmt.Sprintf("Error response from %s, got status: %d", e.URL, e.StatusCode)
}
// RequestBytes does the actual HTTP request.
// Returns a slice of bytes or an error.
func (client *HTTPClient) RequestBytes(ctx context.Context, reqData HTTPRequestData) ([]byte, error) {
span, ctx := opentracing.StartSpanFromContext(ctx, "RequestBytes")
defer span.Finish()
r, err := client.request(ctx, reqData)
if err != nil {
return nil, err
}
defer r.Body.Close()
if r.StatusCode >= 400 {
resp, _ := ioutil.ReadAll(r.Body)
message := string(resp)
span.SetTag("error", true)
span.LogKV("message", fmt.Errorf("error making request to %s, got error: %s", reqData.URL, message))
return nil, HTTPStatusCodeError{
URL: reqData.URL,
StatusCode: r.StatusCode,
Message: message,
}
}
return ioutil.ReadAll(r.Body)
}
func (client *HTTPClient) request(ctx context.Context, reqData HTTPRequestData) (*http.Response, error) {
var req *http.Request
var err error
if reqData.Method == http.MethodPost {
req, err = http.NewRequest(reqData.Method, reqData.URL, bytes.NewBuffer(reqData.PostPayload))
} else {
req, err = http.NewRequest(reqData.Method, reqData.URL, nil)
}
if err != nil {
return nil, err
}
if reqData.GetPayload != nil {
req.URL.RawQuery = reqData.GetPayload.Encode()
}
span := opentracing.SpanFromContext(ctx)
if span != nil {
opentracing.GlobalTracer().Inject(
span.Context(),
opentracing.HTTPHeaders,
opentracing.HTTPHeadersCarrier(req.Header),
)
}
for k, v := range reqData.Headers {
req.Header.Set(k, v)
}
req.Header.Set("User-Agent", "planetposen-mail")
resp, err := client.Do(req)
if err != nil {
if reqData.Method == http.MethodPost {
return resp, fmt.Errorf("Error making request: %v. Body: %s", err, reqData.PostPayload)
}
return resp, fmt.Errorf("Error making request: %v. Query: %v", err, req.URL.RawQuery)
}
return resp, nil
}

View File

@@ -0,0 +1,56 @@
package sendgrid
import (
"context"
"encoding/json"
"fmt"
"github.com/kevinmidboe/planetposen-mail/client"
"github.com/kevinmidboe/planetposen-mail/mail"
"net/http"
)
// SendOrderConfirmation sends an order confirmation.
func (c *Client) SendOrderConfirmation(ctx context.Context, record mail.OrderConfirmationEmailData) error {
reqBody := sendEmailPayload{
Personalizations: []personalization{
{
To: []email{
{
Email: record.ToEmail,
},
},
Subject: record.Subject,
},
},
From: email{
Email: record.FromEmail,
Name: record.FromName,
},
Content: []content{
{
Type: "text/html",
Value: record.Markup,
},
},
}
jsonPayload, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("error marshalling sendEmailPayload: %w", err)
}
reqData := client.HTTPRequestData{
Method: http.MethodPost,
URL: fmt.Sprintf("%s/v3/mail/send", c.Endpoint),
Headers: map[string]string{
"Content-Type": "application/json",
"Authorization": fmt.Sprintf("Bearer %s", c.APIKey),
},
PostPayload: jsonPayload,
}
_, err = c.HTTPClient.RequestBytes(ctx, reqData)
if err != nil {
return fmt.Errorf("error making request to sendgrid to send email: %w", err)
}
return nil
}

View File

@@ -0,0 +1,45 @@
package sendgrid
import (
"time"
"github.com/kevinmidboe/planetposen-mail/client"
"github.com/kevinmidboe/planetposen-mail/config"
)
// Client holds the HTTP client and endpoint information.
type Client struct {
Endpoint string
APIKey string
HTTPClient client.HTTPClient
}
// Init sets up a new sendgrid client.
func (c *Client) Init(config *config.Config) error {
timeout := 5 * time.Second
c.Endpoint = config.SendGridAPIEndpoint
c.APIKey = config.SendGridAPIKey
c.HTTPClient = client.NewHTTPClient(client.Parameters{Timeout: &timeout})
return nil
}
type sendEmailPayload struct {
Personalizations []personalization `json:"personalizations"`
From email `json:"from"`
Content []content `json:"content"`
}
type personalization struct {
To []email `json:"to"`
Subject string `json:"subject"`
}
type email struct {
Email string `json:"email"`
Name string `json:"name"`
}
type content struct {
Type string `json:"type"`
Value string `json:"value"`
}