Implement mailto barcodes and corresponding test

This commit is contained in:
Fred Boniface 2023-09-05 12:05:04 +01:00
parent d07ccd7038
commit cfb0d4ebc6
2 changed files with 96 additions and 0 deletions

48
formatting/email.go Normal file
View File

@ -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
}

48
formatting/email_test.go Normal file
View File

@ -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)
}
}
}