udemy-go-microservices/mail-service/cmd/api/handlers.go
2024-09-03 21:09:34 +02:00

55 lines
1.1 KiB
Go

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