Skip to content

Commit 228d3b0

Browse files
committed
Fix L3: add apiConfig and JSON helpers; complete handler_notes
1 parent d4db4c6 commit 228d3b0

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

apiconfig.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package main
2+
3+
import "github.com/bootdotdev/learn-cicd-starter/internal/database"
4+
5+
// Minimal apiConfig so handlers with receiver *apiConfig compile.
6+
type apiConfig struct {
7+
DB *database.Queries
8+
}

handler_notes.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"github.com/google/uuid"
1010
)
1111

12+
// handlerNotesGet returns all notes for a user
1213
func (cfg *apiConfig) handlerNotesGet(w http.ResponseWriter, r *http.Request, user database.User) {
1314
posts, err := cfg.DB.GetNotesForUser(r.Context(), user.ID)
1415
if err != nil {
@@ -25,15 +26,17 @@ func (cfg *apiConfig) handlerNotesGet(w http.ResponseWriter, r *http.Request, us
2526
respondWithJSON(w, http.StatusOK, postsResp)
2627
}
2728

29+
// handlerNotesCreate creates a new note for a user
2830
func (cfg *apiConfig) handlerNotesCreate(w http.ResponseWriter, r *http.Request, user database.User) {
2931
type parameters struct {
3032
Note string `json:"note"`
3133
}
34+
3235
decoder := json.NewDecoder(r.Body)
3336
params := parameters{}
3437
err := decoder.Decode(&params)
3538
if err != nil {
36-
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters", err)
39+
respondWithError(w, http.StatusBadRequest, "Couldn't decode parameters", err)
3740
return
3841
}
3942

helpers.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
)
7+
8+
// respondWithError sends a JSON error with optional internal details.
9+
func respondWithError(w http.ResponseWriter, code int, message string, err error) {
10+
payload := map[string]string{"error": message}
11+
if err != nil {
12+
payload["details"] = err.Error()
13+
}
14+
respondWithJSON(w, code, payload)
15+
}
16+
17+
// respondWithJSON writes v as JSON with proper error handling (gosec-safe).
18+
func respondWithJSON(w http.ResponseWriter, code int, v any) {
19+
w.Header().Set("Content-Type", "application/json")
20+
w.WriteHeader(code)
21+
22+
data, err := json.Marshal(v)
23+
if err != nil {
24+
http.Error(w, "marshal error", http.StatusInternalServerError)
25+
return
26+
}
27+
if _, err := w.Write(data); err != nil {
28+
http.Error(w, "write error", http.StatusInternalServerError)
29+
return
30+
}
31+
}

0 commit comments

Comments
 (0)