90 lines
2.5 KiB
Go
90 lines
2.5 KiB
Go
package guestbook
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"git.hatecomputers.club/hatecomputers/hatecomputers.club/api/types"
|
|
"git.hatecomputers.club/hatecomputers/hatecomputers.club/database"
|
|
"git.hatecomputers.club/hatecomputers/hatecomputers.club/utils"
|
|
)
|
|
|
|
func SignGuestbookContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
|
|
return func(success types.Continuation, failure types.Continuation) types.ContinuationChain {
|
|
name := req.FormValue("name")
|
|
message := req.FormValue("message")
|
|
|
|
formErrors := types.BannerMessages{
|
|
Messages: []string{},
|
|
}
|
|
|
|
entry := &database.GuestbookEntry{
|
|
ID: utils.RandomId(),
|
|
Name: name,
|
|
Message: message,
|
|
}
|
|
formErrors.Messages = append(formErrors.Messages, validateGuestbookEntry(entry)...)
|
|
|
|
if len(formErrors.Messages) == 0 {
|
|
_, err := database.SaveGuestbookEntry(context.DBConn, entry)
|
|
if err != nil {
|
|
log.Println(err)
|
|
formErrors.Messages = append(formErrors.Messages, "failed to save entry")
|
|
}
|
|
}
|
|
|
|
if len(formErrors.Messages) > 0 {
|
|
(*context.TemplateData)["Error"] = formErrors
|
|
(*context.TemplateData)["EntryForm"] = entry
|
|
resp.WriteHeader(http.StatusBadRequest)
|
|
|
|
return failure(context, req, resp)
|
|
}
|
|
|
|
formSuccess := types.BannerMessages{
|
|
Messages: []string{"entry added."},
|
|
}
|
|
(*context.TemplateData)["Success"] = formSuccess
|
|
return success(context, req, resp)
|
|
}
|
|
}
|
|
|
|
func ListGuestbookContinuation(context *types.RequestContext, req *http.Request, resp http.ResponseWriter) types.ContinuationChain {
|
|
return func(success types.Continuation, failure types.Continuation) types.ContinuationChain {
|
|
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
|
|
}
|