gophertype/pkg/controllers/contact.go
Noah Petherbridge 898f82fb79 Modernize Backend Go App
* Remove Negroni in favor of the standard net/http server.
* Remove gorilla/mux in favor of the standard net/http NewServeMux.
* Remove gorilla/sessions in favor of Redis session_id cookie.
* Remove the hacky glue controllers setup in favor of regular defined routes
  in the router.go file directly.
* Update all Go dependencies for Go 1.24
* Move and centralize all the HTTP middlewares.
* Add middlewares for Logging and Recovery to replace Negroni's.
2025-04-03 22:45:34 -07:00

82 lines
1.9 KiB
Go

package controllers
import (
"fmt"
"html/template"
"net/http"
"git.kirsle.net/apps/gophertype/pkg/mail"
"git.kirsle.net/apps/gophertype/pkg/markdown"
"git.kirsle.net/apps/gophertype/pkg/responses"
"git.kirsle.net/apps/gophertype/pkg/session"
"git.kirsle.net/apps/gophertype/pkg/settings"
"github.com/albrow/forms"
)
// ContactHandler receives admin emails from users.
func ContactHandler(w http.ResponseWriter, r *http.Request) {
var (
v = responses.NewTemplateVars(w, r)
ses = session.Get(r)
)
// Load their cached name from any previous comments they may have posted.
name := ses.Name
email := ses.Email
for r.Method == http.MethodPost {
// Validate form parameters.
form, _ := forms.Parse(r)
val := form.Validator()
val.Require("message")
if val.HasErrors() {
v.ValidationError = val.ErrorMap()
v.V["Error"] = "Missing required form fields."
break
}
var (
name = form.Get("name")
email = form.Get("email")
subject = form.Get("subject")
message = form.Get("message")
)
// Cache their name in their session for future comments/asks.
ses.Name = name
ses.Email = email
ses.Save(w)
// Email the site admin.
if name == "" {
name = "Anonymous"
}
if subject == "" {
subject = "No Subject"
}
go mail.EmailAdmins(mail.Email{
Subject: fmt.Sprintf("Contact Me (%s) from %s: %s", settings.Current.Title, name, subject),
Template: "_builtin/email/generic.gohtml",
Data: map[string]interface{}{
"Subject": subject,
"ReplyTo": email,
"Message": template.HTML(
markdown.RenderMarkdown(fmt.Sprintf(
"Subject: %s\nSender name: %s\nSender email: %s\n\n%s\n",
subject, name, email, message,
)),
),
},
})
session.Flash(w, r, "Thank you! Your message has been e-mailed to the site owner.")
responses.Redirect(w, r, "/contact")
return
}
v.V["name"] = name
v.V["email"] = email
responses.RenderTemplate(w, r, "_builtin/contact.gohtml", v)
}