From cfb0d4ebc67f47014562b69b16d567736fd58934 Mon Sep 17 00:00:00 2001 From: Fred Boniface Date: Tue, 5 Sep 2023 12:05:04 +0100 Subject: [PATCH] Implement mailto barcodes and corresponding test --- formatting/email.go | 48 ++++++++++++++++++++++++++++++++++++++++ formatting/email_test.go | 48 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 formatting/email.go create mode 100644 formatting/email_test.go diff --git a/formatting/email.go b/formatting/email.go new file mode 100644 index 0000000..55981a0 --- /dev/null +++ b/formatting/email.go @@ -0,0 +1,48 @@ +package formatting + +import ( + "encoding/json" + "net/url" +) + +type EMail struct { + Address string `json:"address,omitempty"` + Cc *string `json:"cc,omitempty"` + Bcc *string `json:"bcc,omitempty"` + Subject *string `json:"subject,omitempty"` + Content *string `json:"content,omitempty"` +} + +func formatEMail(input string) (string, error) { + var email EMail + err := json.Unmarshal([]byte(input), &email) + if err != nil { + return "", err + } + + query := url.Values{} + + if email.Subject != nil { + query.Add("subject", *email.Subject) + } + + if email.Cc != nil { + query.Add("cc", *email.Cc) + } + + if email.Bcc != nil { + query.Add("bcc", *email.Bcc) + } + + if email.Content != nil { + query.Add("body", *email.Content) + } + + barcodeString := "mailto:" + email.Address + + if len(query) > 0 { + barcodeString += "?" + query.Encode() + } + + return barcodeString, err +} diff --git a/formatting/email_test.go b/formatting/email_test.go new file mode 100644 index 0000000..d70c1ff --- /dev/null +++ b/formatting/email_test.go @@ -0,0 +1,48 @@ +package formatting + +import ( + "testing" +) + +func TestFormatEmail(t *testing.T) { + testCases := []struct { + inputJSON string + expectedURL string + }{ + { + inputJSON: `{ + "address": "testing@example.com" + }`, + expectedURL: "mailto:testing@example.com", + }, + { + inputJSON: `{ + "address": "testing@example.com", + "subject": "Hello", + "cc": "cc@example.com" + }`, + expectedURL: "mailto:testing@example.com?cc=cc%40example.com&subject=Hello", + }, + { + inputJSON: `{ + "address": "testing@example.com", + "subject": "Subject", + "cc": "cc@example.com", + "bcc": "bcc@example.com", + "content": "this is email content" + }`, + expectedURL: "mailto:testing@example.com?bcc=bcc%40example.com&body=this+is+email+content&cc=cc%40example.com&subject=Subject", + }, + } + + for _, testCase := range testCases { + result, err := formatEMail(testCase.inputJSON) + if err != nil { + t.Errorf("Unexpected Error: %v", err) + } + + if result != testCase.expectedURL { + t.Errorf("Input JSON: \n%s\n\nExpected: %s\n\n Got: %s", testCase.inputJSON, testCase.expectedURL, result) + } + } +}