hatecomputers.club/api/guestbook/guestbook.go

90 lines
2.5 KiB
Go
Raw Permalink Normal View History

2024-04-03 19:53:50 -04:00
package guestbook
2024-03-29 18:35:04 -04:00
import (
"log"
"net/http"
"strings"
2024-04-03 19:53:50 -04:00
"git.hatecomputers.club/hatecomputers/hatecomputers.club/api/types"
2024-03-29 18:35:04 -04:00
"git.hatecomputers.club/hatecomputers/hatecomputers.club/database"
"git.hatecomputers.club/hatecomputers/hatecomputers.club/utils"
)
2024-04-03 19:53:50 -04:00
func SignGuestbookContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
return func(success types.Continuation, failure types.Continuation) types.ContinuationChain {
2024-03-29 18:35:04 -04:00
name := req.FormValue("name")
message := req.FormValue("message")
formErrors := types.BannerMessages{
Messages: []string{},
2024-03-29 18:35:04 -04:00
}
entry := &database.GuestbookEntry{
ID: utils.RandomId(),
Name: name,
Message: message,
}
formErrors.Messages = append(formErrors.Messages, validateGuestbookEntry(entry)...)
2024-03-29 18:35:04 -04:00
if len(formErrors.Messages) == 0 {
2024-04-03 17:58:44 -04:00
_, err := database.SaveGuestbookEntry(context.DBConn, entry)
if err != nil {
log.Println(err)
formErrors.Messages = append(formErrors.Messages, "failed to save entry")
2024-04-03 17:58:44 -04:00
}
2024-03-31 13:47:54 -04:00
}
2024-04-03 17:58:44 -04:00
if len(formErrors.Messages) > 0 {
(*context.TemplateData)["Error"] = formErrors
2024-03-31 13:47:54 -04:00
(*context.TemplateData)["EntryForm"] = entry
2024-04-03 17:58:44 -04:00
resp.WriteHeader(http.StatusBadRequest)
2024-03-29 18:35:04 -04:00
return failure(context, req, resp)
}
formSuccess := types.BannerMessages{
Messages: []string{"entry added."},
}
(*context.TemplateData)["Success"] = formSuccess
2024-03-29 18:35:04 -04:00
return success(context, req, resp)
}
}
2024-04-03 19:53:50 -04:00
func ListGuestbookContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
return func(success types.Continuation, failure types.Continuation) types.ContinuationChain {
2024-03-29 18:35:04 -04:00
entries, err := database.GetGuestbookEntries(context.DBConn)
if err != nil {
log.Println(err)
resp.WriteHeader(http.StatusInternalServerError)
return failure(context, req, resp)
}
(*context.TemplateData)["GuestbookEntries"] = entries
return success(context, req, resp)
}
}
func validateGuestbookEntry(entry *database.GuestbookEntry) []string {
errors := []string{}
if entry.Name == "" {
errors = append(errors, "name is required")
}
if entry.Message == "" {
errors = append(errors, "message is required")
}
messageLength := len(entry.Message)
if messageLength > 500 {
errors = append(errors, "message cannot be longer than 500 characters")
}
newLines := strings.Count(entry.Message, "\n")
if newLines > 10 {
errors = append(errors, "message cannot contain more than 10 new lines")
}
return errors
}