func main() { err := godotenv.Load() if err != nil { log.Println("Error loading .env file") } // Create a new instance of Frodo App := Frodo.New() // Add the root route App.Get("/", func(w http.ResponseWriter, r *Frodo.Request) { w.Write([]byte("Hello World!!!")) }) App.Post("/", &controller.Home{}, Frodo.Use{ Method: "Index", }) // Specify PORT as an environment variable // Necessary for running on Heroku port := "3102" if os.Getenv("PORT") != "" { port = os.Getenv("PORT") } App.ServeOnPort(port) }
func init() { godotenv.Load() }
// Index defines the Post request handler func (h *Home) Index(w http.ResponseWriter, r *Frodo.Request) { err := godotenv.Load() if err != nil { log.Println("Error loading .env file") } // Decode the JSON from the POST request body decoder := json.NewDecoder(r.Body) // Initialize a new newsletter struct var t newsletter decodeErr := decoder.Decode(&t) if decodeErr != nil { panic(decodeErr) } recipients := t.Subscribers sender := os.Getenv("SENDER_ADDRESS") workerCount := 8 debug := true mailer := mail.NewMailer( os.Getenv("SMTP_USERNAME"), os.Getenv("SMTP_PASSWORD"), os.Getenv("SMTP_HOST"), os.Getenv("SMTP_PORT"), ) jobs := make(chan string, len(recipients)) success := make(chan *email.Email) fail := make(chan error) htmlContent := t.Content subject := t.Title // Start workers for i := 0; i < workerCount; i++ { go func() { for recipient := range jobs { sendMail(sender, recipient, subject, htmlContent, &mailer, debug, success, fail) } }() } // Send jobs to workers for _, recipient := range recipients { jobs <- recipient } close(jobs) for i := 0; i < len(recipients); i++ { select { case msg := <-success: if debug { fmt.Printf("\rEmailed recipient %d of %d...", i+1, len(recipients)) } else { bytes, err := msg.Bytes() if err != nil { fmt.Printf("Error parsing email: %v", err) } fmt.Printf("%s\n\n\n", string(bytes)) } case err := <-fail: fmt.Fprintln(os.Stderr, "\nError sending email:", err.Error()) os.Exit(2) } } fmt.Println() w.Write([]byte("Newsletter Successfully Sent!")) }