-
Notifications
You must be signed in to change notification settings - Fork 0
/
product.go
82 lines (73 loc) · 2.2 KB
/
product.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package handler
import (
"database/sql"
"encoding/json"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
"github.com/tonnytg/waffle/adapters/db"
"github.com/tonnytg/waffle/adapters/dto"
"github.com/tonnytg/waffle/application"
"log"
"net/http"
)
func MakeProductHandlers(r *mux.Router, n *negroni.Negroni, service application.ProductServiceInterface) {
r.Handle("/product/{id}", n.With(
negroni.Wrap(getProduct(service)),
)).Methods("GET", "OPTIONS")
r.Handle("/product", n.With(
negroni.Wrap(createProduct(service)),
)).Methods("POST", "OPTIONS")
}
func createProduct(service application.ProductServiceInterface) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := sql.Open(db.DatabaseDriver, db.DataSourceName)
if err != nil {
log.Fatal(err)
}
productDbAdapter := db.NewProductDb(conn)
productService := application.NewProductService(productDbAdapter)
w.Header().Set("Content-Type", "application/json")
var productDto dto.Product
err = json.NewDecoder(r.Body).Decode(&productDto)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write(jsonError(err.Error()))
return
}
product, err := productService.Create(productDto.Name, productDto.Price)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write(jsonError(err.Error()))
return
}
err = json.NewEncoder(w).Encode(product)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write(jsonError(err.Error()))
return
}
})
}
func getProduct(service application.ProductServiceInterface) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := sql.Open(db.DatabaseDriver, db.DataSourceName)
if err != nil {
log.Fatal(err)
}
productDbAdapter := db.NewProductDb(conn)
productService := application.NewProductService(productDbAdapter)
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
id := vars["id"]
product, err := productService.Get(id)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
err = json.NewEncoder(w).Encode(product)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
})
}