/
get.go
66 lines (50 loc) · 1.63 KB
/
get.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package handlers
import (
"net/http"
"github.com/gmgale/go_micro/8_Auto-generating_HTTP_clients_from_Swagger_files/data"
)
// swagger:route GET /products products listProducts
// Return a list of products from the database
// responses:
// 200: productsResponse
// ListAll handles GET requests and returns all current products
func (p *Products) ListAll(rw http.ResponseWriter, r *http.Request) {
p.l.Println("[DEBUG] get all records")
rw.Header().Add("Content-Type", "application/json")
prods := data.GetProducts()
err := data.ToJSON(prods, rw)
if err != nil {
// we should never be here but log the error just incase
p.l.Println("[ERROR] serializing product", err)
}
}
// swagger:route GET /products/{id} products listSingleProduct
// Return a list of products from the database
// responses:
// 200: productResponse
// 404: errorResponse
// ListSingle handles GET requests
func (p *Products) ListSingle(rw http.ResponseWriter, r *http.Request) {
rw.Header().Add("Content-Type", "application/json")
id := getProductID(r)
p.l.Println("[DEBUG] get record id", id)
prod, err := data.GetProductByID(id)
switch err {
case nil:
case data.ErrProductNotFound:
p.l.Println("[ERROR] fetching product", err)
rw.WriteHeader(http.StatusNotFound)
data.ToJSON(&GenericError{Message: err.Error()}, rw)
return
default:
p.l.Println("[ERROR] fetching product", err)
rw.WriteHeader(http.StatusInternalServerError)
data.ToJSON(&GenericError{Message: err.Error()}, rw)
return
}
err = data.ToJSON(prod, rw)
if err != nil {
// we should never be here but log the error just incase
p.l.Println("[ERROR] serializing product", err)
}
}