-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
37 lines (30 loc) · 830 Bytes
/
handlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main
import (
"encoding/json"
"github.com/gorilla/mux"
"net/http"
"strconv"
)
func respondWithError(w http.ResponseWriter, code int, message string) {
respondWithJSON(w, code, map[string]string{"error": message})
}
func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
func (a *App) getProduct(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid product ID")
return
}
p, err := getProduct(a.DB, id)
if err != nil {
respondWithError(w, http.StatusNotFound, "Product not found")
return
}
respondWithJSON(w, http.StatusOK, p)
}