From cb425edd8b8a82800ac3c40cb2c4af636bc182df Mon Sep 17 00:00:00 2001 From: Jack Punter Date: Tue, 23 Apr 2024 23:38:44 +0100 Subject: [PATCH] Migrate to the new toml file for config from the go email sender --- .gitignore | 2 +- go.mod | 2 +- go.sum | 22 ++++++++++-- main.go | 97 +++++++++++++++++++---------------------------------- postmark.go | 12 +++---- 5 files changed, 62 insertions(+), 73 deletions(-) diff --git a/.gitignore b/.gitignore index 344672f..58f4a89 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ tmp/ -app.ini \ No newline at end of file +app.toml \ No newline at end of file diff --git a/go.mod b/go.mod index ef4a8bf..15e34b7 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,4 @@ module send_email_site go 1.21.6 -require gopkg.in/ini.v1 v1.67.0 // indirect +require github.com/pelletier/go-toml/v2 v2.2.1 diff --git a/go.sum b/go.sum index a8937af..02a16d6 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,20 @@ -gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= -gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pelletier/go-toml/v2 v2.2.1 h1:9TA9+T8+8CUCO2+WYnDLCgrYi9+omqKXyjDtosvtEhg= +github.com/pelletier/go-toml/v2 v2.2.1/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index 73dfbd7..df42c20 100644 --- a/main.go +++ b/main.go @@ -15,73 +15,44 @@ import ( "strings" "time" - "gopkg.in/ini.v1" + "github.com/pelletier/go-toml/v2" ) // ------------- Api configs ------------- -type DefaultSectionConfig struct { - Live bool - TestEmail string - SenderName string -} - -type HMCConfig struct { - ApiSecret string - ApiUrl string - City string -} - -type PostmarkConfig struct { - ServerToken string - ApiUrl string - TemplateId int - SenderEmail string - MessageStream string -} - type ApiConfig struct { - Default DefaultSectionConfig - Hmc HMCConfig - Postmark PostmarkConfig + BatchSize int `toml:"batch_size"` + TestEmail string `toml:"test_email"` + HMC struct { + ApiUrl string `toml:"api_url"` + SharedSecret string `toml:"shared_secret"` + City string `toml:"city"` + } `toml:"hmc"` + Postmark struct { + ServerToken string `toml:"server_token"` + ApiUrl string `toml:"api_url"` + TemplateId int `toml:"template_id"` + SenderName string `toml:"sender_name"` + SenderEmail string `toml:"sender_email"` + MessageStream string `toml:"message_stream"` + } `toml:"postmark"` } // Load the HMCsend-email app.ini and store the values in a structure, some of the keys in here // we probably don't actualy care about for this usage. func loadConfig() ApiConfig { - // Read the config file and get the HMC api settings - config, err := ini.Load("app.ini") + configFile := "app.toml" + data, err := os.ReadFile(configFile) if err != nil { - panic(err) + fmt.Println("Error reading TOML file:", err) + os.Exit(1) } - defSection := config.Section("DEFAULT") - def := DefaultSectionConfig{ - Live: defSection.Key("LIVE").MustBool(), - TestEmail: defSection.Key("TEST_EMAIL").String(), - SenderName: defSection.Key("SENDER_NAME").String(), - } - - hmcSection := config.Section("hmc") - hmc := HMCConfig{ - ApiSecret: hmcSection.Key("SHARED_SECRET").String(), - ApiUrl: hmcSection.Key("API_URL").String(), - City: hmcSection.Key("CITY").String(), - } - - postmarkSection := config.Section("postmark") - postmark := PostmarkConfig{ - ServerToken: postmarkSection.Key("SERVER_TOKEN").String(), - ApiUrl: postmarkSection.Key("API_URL").String(), - TemplateId: postmarkSection.Key("TEMPLATE_ID").MustInt(), - SenderEmail: postmarkSection.Key("SENDER_EMAIL").String(), - MessageStream: postmarkSection.Key("MESSAGE_STREAM").String(), - } - - return ApiConfig{ - Default: def, - Hmc: hmc, - Postmark: postmark, + config := ApiConfig{} + if err := toml.Unmarshal(data, &config); err != nil { + fmt.Println("Error unmarshaling TOML:", err) + os.Exit(1) } + return config } func ParseArguments(rawArgs string) map[string]string { @@ -101,14 +72,14 @@ func GetMailingList(cfg ApiConfig) []string { type EmailsResonse struct { Emails []string `json:"emails"` } - body := []byte(fmt.Sprintf("{\"city\": \"%s\"}", cfg.Hmc.City)) - req, err := http.NewRequest("POST", cfg.Hmc.ApiUrl, bytes.NewBuffer(body)) + body := []byte(fmt.Sprintf("{\"city\": \"%s\"}", cfg.HMC.City)) + req, err := http.NewRequest("POST", cfg.HMC.ApiUrl, bytes.NewBuffer(body)) if err != nil { panic(err) } req.Header.Add("Content-Type", "application/json") - req.Header.Add("Authorization", cfg.Hmc.ApiSecret) + req.Header.Add("Authorization", cfg.HMC.SharedSecret) client := &http.Client{} res, err := client.Do(req) @@ -127,7 +98,7 @@ func GetMailingList(cfg ApiConfig) []string { func main() { apiConfig := loadConfig() - postmarkTemplate := getPostmarkTemplate(apiConfig.Postmark) + postmarkTemplate := getPostmarkTemplate(apiConfig) // Prepare the go html templates and static file server templates := template.Must(template.ParseGlob("templates/*.html")) @@ -160,13 +131,13 @@ func main() { // Return a response to HTMX model := PostmarkTemplateModel{ - Name: apiConfig.Default.SenderName, + Name: apiConfig.Postmark.SenderName, Email: apiConfig.Postmark.SenderEmail, Body: email_content, Subject: "This is a test subject", // TODO(jack): Get from user input on page } - renderedEmail := renderPostmarkTemplate(apiConfig.Postmark, postmarkTemplate, model) + renderedEmail := renderPostmarkTemplate(apiConfig, postmarkTemplate, model) w.Write([]byte(renderedEmail.Html)) }) @@ -186,12 +157,12 @@ func main() { } model := PostmarkTemplateModel{ - Name: apiConfig.Default.SenderName, + Name: apiConfig.Postmark.SenderName, Email: apiConfig.Postmark.SenderEmail, Body: "", Subject: decoded_subject, // TODO(jack): Get from user input on page } - renderedEmail := renderPostmarkTemplate(apiConfig.Postmark, postmarkTemplate, model) + renderedEmail := renderPostmarkTemplate(apiConfig, postmarkTemplate, model) w.Write([]byte(renderedEmail.Subject)) }) @@ -217,7 +188,7 @@ func main() { fmt.Printf("%v\n", arguments) var recipients []string if arguments["destination"] == "test" { - recipients = []string{apiConfig.Default.TestEmail} + recipients = []string{apiConfig.TestEmail} } else if arguments["destination"] == "mailing_list" { recipients = GetMailingList(apiConfig) } else { diff --git a/postmark.go b/postmark.go index fe1e2f7..538db0a 100644 --- a/postmark.go +++ b/postmark.go @@ -71,15 +71,15 @@ type Email struct { } // Gets the tempalte in the postmark config section of the app.ini file from teh postmark server so we can render it -func getPostmarkTemplate(cfg PostmarkConfig) PostmarkTemplate { +func getPostmarkTemplate(cfg ApiConfig) PostmarkTemplate { // Get Template - getTemplateURL := fmt.Sprintf("https://api.postmarkapp.com/templates/%v", cfg.TemplateId) + getTemplateURL := fmt.Sprintf("https://api.postmarkapp.com/templates/%v", cfg.Postmark.TemplateId) getReq, err := http.NewRequest(http.MethodGet, getTemplateURL, bytes.NewBuffer([]byte(""))) if err != nil { panic(err) } getReq.Header.Add("Accept", "application/json") - getReq.Header.Add("X-Postmark-Server-Token", cfg.ServerToken) + getReq.Header.Add("X-Postmark-Server-Token", cfg.Postmark.ServerToken) client := &http.Client{} getResp, err := client.Do(getReq) @@ -98,7 +98,7 @@ func getPostmarkTemplate(cfg PostmarkConfig) PostmarkTemplate { } // Given a tempalte and model use the postmark tempalte validation api to render the template -func renderPostmarkTemplate(cfg PostmarkConfig, template PostmarkTemplate, model PostmarkTemplateModel) Email { +func renderPostmarkTemplate(cfg ApiConfig, template PostmarkTemplate, model PostmarkTemplateModel) Email { bodyObj := ValidateTemplateBody{ Subject: template.Subject, HTMLBody: template.HtmlBody, @@ -118,7 +118,7 @@ func renderPostmarkTemplate(cfg PostmarkConfig, template PostmarkTemplate, model req.Header.Add("Content-Type", "application/json") req.Header.Add("Accept", "application/json") - req.Header.Add("X-Postmark-Server-Token", cfg.ServerToken) + req.Header.Add("X-Postmark-Server-Token", cfg.Postmark.ServerToken) client := &http.Client{} resp, err := client.Do(req) @@ -163,7 +163,7 @@ func sendBatchWithTemplate(cfg ApiConfig, email, subject string, recipients []st To: recipient, TemplateId: cfg.Postmark.TemplateId, TemplateModel: PostmarkTemplateModel{ - Name: cfg.Default.SenderName, + Name: cfg.Postmark.SenderName, Email: cfg.Postmark.SenderEmail, Body: email, Subject: subject,