saasitone/pkg/handlers/contact.go

79 lines
1.6 KiB
Go
Raw Permalink Normal View History

package handlers
2021-12-03 03:11:01 -08:00
import (
"fmt"
2024-07-09 17:57:05 -07:00
"github.com/go-playground/validator/v10"
"github.com/labstack/echo/v4"
2024-07-09 17:57:05 -07:00
"git.grosinger.net/tgrosinger/saasitone/pkg/form"
"git.grosinger.net/tgrosinger/saasitone/pkg/page"
"git.grosinger.net/tgrosinger/saasitone/pkg/services"
2024-07-14 19:50:58 -07:00
"git.grosinger.net/tgrosinger/saasitone/templ/layouts"
"git.grosinger.net/tgrosinger/saasitone/templ/pages"
)
2021-12-03 03:11:01 -08:00
const (
routeNameContact = "contact"
routeNameContactSubmit = "contact.submit"
2021-12-03 03:11:01 -08:00
)
2021-12-22 18:51:18 -08:00
type (
Contact struct {
mail *services.MailClient
*services.TemplateRenderer
2021-12-22 18:51:18 -08:00
}
)
func init() {
Register(new(Contact))
}
func (h *Contact) Init(c *services.Container) error {
h.TemplateRenderer = c.TemplateRenderer
h.mail = c.Mail
return nil
}
func (h *Contact) Routes(g *echo.Group) {
g.GET("/contact", h.Page).Name = routeNameContact
g.POST("/contact", h.Submit).Name = routeNameContactSubmit
}
func (h *Contact) Page(ctx echo.Context) error {
p := page.New(ctx)
p.Title = "Contact us"
p.LayoutComponent = layouts.Main
2021-12-22 18:51:18 -08:00
2024-07-14 19:50:58 -07:00
f := form.Get[pages.ContactForm](ctx)
component := pages.Contact(p, f)
return h.RenderPageTempl(ctx, p, component)
2021-12-03 03:11:01 -08:00
}
func (h *Contact) Submit(ctx echo.Context) error {
2024-07-14 19:50:58 -07:00
var input pages.ContactForm
2021-12-23 20:04:00 -08:00
err := form.Submit(ctx, &input)
switch err.(type) {
case nil:
case validator.ValidationErrors:
return h.Page(ctx)
default:
return err
2021-12-22 18:51:18 -08:00
}
err = h.mail.
Compose().
To(input.Email).
Subject("Contact form submitted").
Body(fmt.Sprintf("The message is: %s", input.Message)).
Send(ctx)
if err != nil {
return fail(err, "unable to send email")
2021-12-22 18:51:18 -08:00
}
return h.Page(ctx)
2021-12-03 03:11:01 -08:00
}