-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
138 lines (121 loc) · 3.43 KB
/
app.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
)
type App struct {
Router *mux.Router
DB *sql.DB
}
func (app *App) Initialise(DbUser, DbPassword, DbName string) error {
connectionString := fmt.Sprintf("%v:%v@tcp(127.0.0.1:3306)/%v", DbUser, DbPassword, DbName)
var err error
app.DB, err = sql.Open("mysql", connectionString)
if err != nil {
return err
}
app.Router = mux.NewRouter().StrictSlash(true)
app.handleRoutes()
return nil
}
func (app *App) Run(address string) {
log.Fatal(http.ListenAndServe(address, app.Router))
}
func sendResponse(w http.ResponseWriter, statusCode int, payload interface{}) {
res, _ := json.Marshal(payload)
w.Header().Set("Content-type", "application/json")
w.WriteHeader(statusCode)
w.Write(res)
}
func sendError(w http.ResponseWriter, statusCode int, err string) {
errMessage := map[string]string{"error": err}
sendResponse(w, statusCode, errMessage)
}
func (app *App) getProducts(w http.ResponseWriter, r *http.Request) {
products, err := getProducts(app.DB)
if err != nil {
sendError(w, http.StatusInternalServerError, err.Error())
return
}
sendResponse(w, http.StatusOK, products)
}
func (app *App) getProduct(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key, err := strconv.Atoi(vars["id"])
if err != nil {
sendError(w, http.StatusBadRequest, "invalid product ID")
}
p := product{ID: key}
err = p.getProduct(app.DB)
if err != nil {
switch err {
case sql.ErrNoRows:
sendError(w, http.StatusNotFound, "Product not found")
default:
sendError(w, http.StatusInternalServerError, err.Error())
}
return
}
sendResponse(w, http.StatusOK, p)
}
func (app *App) createProduct(w http.ResponseWriter, r *http.Request) {
var p product
err := json.NewDecoder(r.Body).Decode(&p)
if err != nil {
sendError(w, http.StatusBadRequest, "Invalid request payload")
return
}
err = p.createProduct(app.DB)
if err != nil {
sendError(w, http.StatusInternalServerError, err.Error())
return
}
sendResponse(w, http.StatusCreated, p)
}
func (app *App) updateProduct(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key, err := strconv.Atoi(vars["id"])
if err != nil {
sendError(w, http.StatusBadRequest, "invalid product ID")
}
var p product
err = json.NewDecoder(r.Body).Decode(&p)
if err != nil {
sendError(w, http.StatusBadRequest, "Invalid request payload")
return
}
p.ID = key
err = p.updateProduct(app.DB)
if err != nil {
sendError(w, http.StatusInternalServerError, err.Error())
return
}
sendResponse(w, http.StatusOK, p)
}
func (app *App) deleteProduct(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key, err := strconv.Atoi(vars["id"])
if err != nil {
sendError(w, http.StatusBadRequest, "invalid product ID")
}
p := product{ID: key}
err = p.deleteProduct(app.DB)
if err != nil {
sendError(w, http.StatusInternalServerError, err.Error())
return
}
sendResponse(w, http.StatusOK, map[string]string{"result": "success"})
}
func (app *App) handleRoutes() {
app.Router.HandleFunc("/products", app.getProducts).Methods("GET")
app.Router.HandleFunc("/product/{id}", app.getProduct).Methods("GET")
app.Router.HandleFunc("/product/{id}", app.updateProduct).Methods("PUT")
app.Router.HandleFunc("/product", app.createProduct).Methods("POST")
app.Router.HandleFunc("/product/{id}", app.deleteProduct).Methods("DELETE")
}