client

package module
v0.0.0-...-2894313 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 13, 2024 License: MIT Imports: 8 Imported by: 0

README

Notification Go Client

This is a Go client for the Government of Canada's Notification API. You can use it for other variants of the Notify API by changing the hostname. ex: c.Hostname = "https://api.notifications.service.gov.uk/"

The client library is designed to be explicit and minimal without significant abstractions. As a result most structs are directly accessible without helper functions such as variardic options in constructors and setters. Additionally there is very light validation on data with a preference for the Notify API to return validation errors.

Initializing the client

import client "github.com/cds-snc/notification-go-client"

func main() {
	api_key := os.Getenv("NOTIFICATION_API_KEY")

	c, err := client.NewClient(api_key)

	if err != nil {
		fmt.Printf("Error creating client: %s", err)
	}

	// Change the hostname if you are using a different environment
	c.Hostname = "https://api.notifications.service.gov.uk/"
	
	// Use the client
	...
}

Sending an email without personalisation

	e := client.Email{
		EmailAddress: "test@test.com",
		TemplateId:   "00000000-0000-0000-0000-000000000000",
	}

	resp, err := c.SendEmail(e)

	if err != nil {
		fmt.Printf("Error sending email: %s", err)
	}

	fmt.Printf("Response: %+v", resp)

Sending an email with personalisation including a file

	e := client.Email{
		EmailAddress: "test@test.com",
		TemplateId:   "00000000-0000-0000-0000-000000000000",,
		Personalisation: map[string]interface{}{
			"subject": "Hello, world!",
			"body":    "This is a test email"
			"application_file": {
				"file": "file as base64 encoded string",
				"filename": "your_custom_filename.pdf",
				"sending_method": "attach",
			}
		},
	}

	resp, err := c.SendEmail(e)

	if err != nil {
		fmt.Printf("Error sending email: %s", err)
	}

	fmt.Printf("Response: %+v", resp)

Sending a bulk email with rows defined

	rows := make([][]string, 2)
	rows[0] = []string{"email_address"}
	rows[1] = []string{"test@test.com"}

	e := client.BulkEmail{
		Name:       "Test",
		TemplateId: "00000000-0000-0000-0000-000000000000",
		Rows: 	    rows,
	}

	resp, err := c.SendEmail(e)

	if err != nil {
		fmt.Printf("Error sending email: %s", err)
	}

	fmt.Printf("Response: %+v", resp)

Sending a bulk email with a CSV string

	csv := "email_address\ntest@test.com"

	e := client.BulkEmail{
		Name:       "Test",
		TemplateId: "00000000-0000-0000-0000-000000000000",
		Csv:        csv,
	}

	resp, err := c.SendEmail(e)

	if err != nil {
		fmt.Printf("Error sending email: %s", err)
	}

	fmt.Printf("Response: %+v", resp)

Sending a SMS message

	s := client.SMS{
		PhoneNumber: "1234567890",
		TemplateId:  "00000000-0000-0000-0000-000000000000",
	}

	resp, err := c.SendSMS(s)

	if err != nil {
		fmt.Printf("Error sending sms: %s", err)
	}

	fmt.Printf("Response: %+v", resp)

Handling errors from the Notify API

	// Send an email with an invalid template ID
	e := client.Email{
		EmailAddress: "test@test.com",
		TemplateId:   "00000000-0000",
	}

	resp, err := c.SendEmail(e)

	// Assume there is no error with the actual request
	if err != nil {
		fmt.Printf("Error sending email: %s", err)
	}

	if resp.StatusCode == 400 {
		fmt.Printf("Error: %s", resp.Errors[0].Message)
	}

Getting the status of notifications

	queryOptions := StatusQueryOptions{
		TemplateType: "email",
	}

	resp, err := c.GetStatus(queryOptions)

	if err != nil {
		fmt.Printf("Error getting status: %s", err)
	}

	// Example of pagination

	fmt.Printf("Page 1: received %d notifications\n", len(resp.Notifications))
	i := 1
	for resp.HasNext() {
		resp, _ = c.NextStatusPage(resp)
		fmt.Printf("Page %d: received %d notifications\n", i+1, len(resp.Notifications))
		i++
	}

Getting the status of a single notification

	notificationId := "00000000-0000-0000-0000-000000000000"

	resp, err := c.GetStatusById(notificationId)

	if err != nil {
		fmt.Printf("Error getting status: %s", err)
	}

	fmt.Printf("Response: %+v", resp)

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BulkEmail

type BulkEmail struct {
	Name       string `json:"name"`
	TemplateId string `json:"template_id"`

	// Optional
	Rows         [][]string `json:"rows,omitempty"`
	ScheduledFor string     `json:"scheduled_for,omitempty"`
	ReplyToId    string     `json:"reply_to_id,omitempty"`
	Csv          string     `json:"csv,omitempty"`
}

type BulkEmailResponse

type BulkEmailResponse struct {
	// Valid Response
	Data bulkEmailDataResponse `json:"data"`

	// Error Response
	StatusCode int             `json:"status_code"`
	Errors     []ResponseError `json:"errors"`
}

type Client

type Client struct {
	ApiKey     string
	HttpClient http.Client
	Hostname   string
}

func NewClient

func NewClient(apiKey string) (Client, error)

func (Client) DoGetRequest

func (c Client) DoGetRequest(endpoint string) (*http.Response, error)

func (Client) DoPostRequest

func (c Client) DoPostRequest(endpoint string, body []byte) (*http.Response, error)

func (Client) GetStatus

func (c Client) GetStatus(options StatusQueryOptions) (StatusResponses, error)

func (Client) GetStatusById

func (c Client) GetStatusById(id string) (StatusResponse, error)

func (Client) NextStatusPage

func (c Client) NextStatusPage(s StatusResponses) (StatusResponses, error)

func (Client) SendBulkEmail

func (c Client) SendBulkEmail(e BulkEmail) (BulkEmailResponse, error)

func (Client) SendEmail

func (c Client) SendEmail(e Email) (Response, error)

func (Client) SendSms

func (c Client) SendSms(s Sms) (Response, error)

type Email

type Email struct {
	EmailAddress string `json:"email_address"`
	TemplateId   string `json:"template_id"`

	// Optional
	EmailReplyToId  string                 `json:"email_reply_to_id,omitempty"`
	Personalisation map[string]interface{} `json:"personalisation,omitempty"`
	Reference       string                 `json:"reference,omitempty"`
}
type Link struct {
	Current string `json:"current"`
	Next    string `json:"next"`
}

type Response

type Response struct {
	// Valid Response
	Id        string            `json:"id"`
	Reference string            `json:"reference"`
	Content   map[string]string `json:"content"`
	Uri       string            `json:"uri"`
	Template  responseTemplate  `json:"template"`

	// Error Response
	StatusCode int             `json:"status_code"`
	Errors     []ResponseError `json:"errors"`
}

type ResponseError

type ResponseError struct {
	Error   string `json:"error"`
	Message string `json:"message"`
}

type Sms

type Sms struct {
	PhoneNumber string `json:"phone_number"`
	TemplateId  string `json:"template_id"`

	// Optional
	SmsSenderId     string            `json:"sms_sender_id,omitempty"`
	Personalisation map[string]string `json:"personalisation,omitempty"`
	Reference       string            `json:"reference,omitempty"`
}

type StatusQueryOptions

type StatusQueryOptions struct {
	OlderThan    string `url:"older_than,omitempty"`
	Reference    string `url:"reference,omitempty"`
	Status       string `url:"status,omitempty"`
	TemplateType string `url:"template_type,omitempty"`
}

type StatusResponse

type StatusResponse struct {
	// Valid Response
	Id                string           `json:"id"`
	Reference         string           `json:"reference"`
	EmailAddress      string           `json:"email_address"`
	PhoneNumber       string           `json:"phone_number"`
	Type              string           `json:"type"`
	Status            string           `json:"status"`
	StatusDescription string           `json:"status_description"`
	ProviderResponse  string           `json:"provider_response"`
	Template          responseTemplate `json:"template"`
	Body              string           `json:"body"`
	Subject           string           `json:"subject"`
	CreatedAt         time.Time        `json:"created_at"`
	CreatedByName     string           `json:"created_by_name"`
	SentAt            time.Time        `json:"sent_at"`
	CompletedAt       time.Time        `json:"completed_at"`

	// Error Response
	StatusCode int             `json:"status_code"`
	Errors     []ResponseError `json:"errors"`
}

type StatusResponses

type StatusResponses struct {
	// Valid Response
	Notifications []StatusResponse `json:"notifications"`
	Links         Link             `json:"links"`

	// Error Response
	StatusCode int             `json:"status_code"`
	Errors     []ResponseError `json:"errors"`
}

func (*StatusResponses) HasNext

func (s *StatusResponses) HasNext() bool

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL