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{}

View File

@@ -40,5 +40,23 @@
"ID": "msg_60f70a47-3be2-4315-869a-d6f151ec262a",
"Timestamp": "2025-03-24T15:01:07.14371835-04:00",
"UserID": 1
},
{
"Body": "ababa abbott",
"ID": "msg_94cbc26d-9098-4fa9-bd21-794516c2263d",
"Timestamp": "2025-03-24T20:34:57.198849367-04:00",
"UserID": 1
},
{
"Body": "AAAAAA",
"ID": "msg_ca8483db-e823-45c4-882c-fe0930610ba9",
"Timestamp": "2025-03-24T21:17:04.350827576-04:00",
"UserID": 1
},
{
"Body": "i am a femboiiiii",
"ID": "msg_fcdbb48a-4ea5-4fb3-b925-3a15eb7c291c",
"Timestamp": "2025-03-24T21:27:48.565290147-04:00",
"UserID": 2
}
]