saasitone/pkg/handlers/contact.go

89 lines
2.0 KiB
Go
Raw Normal View History

package handlers
2021-12-03 03:11:01 -08:00
import (
"fmt"
"github.com/labstack/echo/v4"
2022-11-02 16:23:26 -07:00
"github.com/mikestefanello/pagoda/pkg/context"
"github.com/mikestefanello/pagoda/pkg/controller"
"github.com/mikestefanello/pagoda/pkg/services"
"github.com/mikestefanello/pagoda/templates"
)
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
2021-12-22 18:51:18 -08:00
controller.Controller
}
2021-12-03 03:11:01 -08:00
2022-02-10 05:56:07 -08:00
contactForm struct {
Email string `form:"email" validate:"required,email"`
2024-05-18 13:19:27 -07:00
Department string `form:"department" validate:"required,oneof=sales marketing hr"`
Message string `form:"message" validate:"required"`
Submission controller.FormSubmission
2021-12-22 18:51:18 -08:00
}
)
func init() {
Register(new(Contact))
}
func (c *Contact) Init(ct *services.Container) error {
c.Controller = controller.NewController(ct)
c.mail = ct.Mail
return nil
}
func (c *Contact) Routes(g *echo.Group) {
g.GET("/contact", c.Page).Name = routeNameContact
g.POST("/contact", c.Submit).Name = routeNameContactSubmit
}
func (c *Contact) Page(ctx echo.Context) error {
2021-12-28 19:05:20 -08:00
page := controller.NewPage(ctx)
page.Layout = templates.LayoutMain
page.Name = templates.PageContact
2021-12-28 19:05:20 -08:00
page.Title = "Contact us"
2022-02-10 05:56:07 -08:00
page.Form = contactForm{}
2021-12-22 18:51:18 -08:00
if form := ctx.Get(context.FormKey); form != nil {
2022-02-10 05:56:07 -08:00
page.Form = form.(*contactForm)
2021-12-22 18:51:18 -08:00
}
2021-12-28 19:05:20 -08:00
return c.RenderPage(ctx, page)
2021-12-03 03:11:01 -08:00
}
func (c *Contact) Submit(ctx echo.Context) error {
2022-02-10 05:56:07 -08:00
var form contactForm
2021-12-23 20:04:00 -08:00
ctx.Set(context.FormKey, &form)
// Parse the form values
2021-12-22 18:51:18 -08:00
if err := ctx.Bind(&form); err != nil {
return c.Fail(err, "unable to bind form")
2021-12-22 18:51:18 -08:00
}
if err := form.Submission.Process(ctx, form); err != nil {
return c.Fail(err, "unable to process form submission")
}
if !form.Submission.HasErrors() {
err := c.mail.
Compose().
To(form.Email).
Subject("Contact form submitted").
Body(fmt.Sprintf("The message is: %s", form.Message)).
Send(ctx)
if err != nil {
return c.Fail(err, "unable to send email")
}
2021-12-22 18:51:18 -08:00
}
return c.Page(ctx)
2021-12-03 03:11:01 -08:00
}