use form data for new messages

This commit is contained in:
2025-03-24 21:33:56 -04:00
parent 2ec1738721
commit 02643c1197
2 changed files with 40 additions and 5 deletions

View File

@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
@@ -69,16 +70,31 @@ func NewMessage(w http.ResponseWriter, r *http.Request) {
return
}
var msg Message
err := json.NewDecoder(r.Body).Decode(&msg)
err := r.ParseForm()
if err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
http.Error(w, "Unable to parse form", http.StatusBadRequest)
return
}
msg.ID = newMessageID()
userIDStr := r.FormValue("user_id")
userID, err := strconv.ParseInt(userIDStr, 10, 64)
if err != nil {
http.Error(w, "Invalid user ID", http.StatusBadRequest)
return
}
body := r.FormValue("body")
msg.Timestamp = time.Now()
if body == "" {
http.Error(w, "Invalid body", http.StatusBadRequest)
return
}
msg := Message{
ID: newMessageID(),
UserID: userID,
Body: body,
Timestamp: time.Now(),
}
err = dbAddMessage(&msg)
if err != nil {
@@ -86,6 +102,7 @@ func NewMessage(w http.ResponseWriter, r *http.Request) {
return
}
render.Render(w, r, NewMessageResponse(&msg))
}
type messageKey struct{}