tavern/web/publisher.go

74 lines
1.5 KiB
Go

package web
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"go.uber.org/zap"
"github.com/ngerakines/tavern/common"
"github.com/ngerakines/tavern/config"
"github.com/ngerakines/tavern/g"
)
type publisherClient struct {
logger *zap.Logger
httpClient common.HTTPClient
location string
}
func newPublisherClient(logger *zap.Logger, httpClient common.HTTPClient, config config.PublisherConfig) *publisherClient {
if !config.Enabled {
return nil
}
return &publisherClient{
logger: logger,
httpClient: httpClient,
location: config.Location,
}
}
func (c *publisherClient) Send(ctx context.Context, destination, keyID, keyPEM, activityID, payload string) error {
form := url.Values{}
form.Add("destination", destination)
form.Add("key_id", keyID)
form.Add("key", keyPEM)
form.Add("activity_id", activityID)
form.Add("payload", payload)
req, err := http.NewRequestWithContext(ctx, "POST", c.location, strings.NewReader(form.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", g.UserAgent())
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer func() {
if closeErr := resp.Body.Close(); closeErr != nil {
c.logger.Error("unable to close response body", zap.Error(err))
}
}()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusAccepted {
return fmt.Errorf("unexpected status code: %d %s", resp.StatusCode, body)
}
return nil
}