udemy-go-microservices/mail-service/cmd/api/handlers.go

55 lines
1.1 KiB
Go
Raw Normal View History

2024-09-02 18:48:30 +00:00
package main
import (
"errors"
"fmt"
"log"
"net/http"
"github.com/tsawler/toolbox"
)
type MailData struct {
2024-09-02 19:32:59 +00:00
From string `json:"from"`
To string `json:"to"`
Subject string `json:"subject"`
Content string `json:"content"`
2024-09-02 18:48:30 +00:00
}
func (app *Config) SendMail(w http.ResponseWriter, r *http.Request) {
var mailData MailData
2024-09-02 19:32:59 +00:00
err := app.Tools.ReadJSON(w, r, &mailData)
2024-09-02 18:48:30 +00:00
if err != nil {
log.Println(err)
app.Tools.ErrorJSON(w, err)
2024-09-02 19:32:59 +00:00
return
2024-09-02 18:48:30 +00:00
}
2024-09-02 19:32:59 +00:00
log.Println("Sending mail")
2024-09-02 18:48:30 +00:00
if mailData.From == "" || mailData.To == "" ||
(mailData.Subject == "" && mailData.Content == "") {
log.Println("Invalid mail")
app.Tools.ErrorJSON(w, errors.New("invalid mail"), http.StatusBadRequest)
2024-09-02 19:32:59 +00:00
return
2024-09-02 18:48:30 +00:00
}
2024-09-03 19:09:34 +00:00
msg := Message{
From: mailData.From,
To: mailData.To,
Subject: mailData.Subject,
Data: mailData.Content,
}
err = app.Mailer.SendSMTPMessage(msg)
2024-09-02 18:48:30 +00:00
if err != nil {
log.Println(err)
app.Tools.ErrorJSON(w, err)
2024-09-02 19:32:59 +00:00
return
2024-09-02 18:48:30 +00:00
}
var payload toolbox.JSONResponse
payload.Error = false
payload.Message = fmt.Sprintf("mail sent to %s", mailData.To)
2024-09-02 19:32:59 +00:00
app.Tools.WriteJSON(w, http.StatusAccepted, payload)
2024-09-02 18:48:30 +00:00
}