-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
152 lines (134 loc) · 3.66 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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package main
// Demo: Project Setup
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 checkError(e error) error {
if e != nil {
fmt.Println(e)
panic(e)
}
return nil
}
func (app *App) Initialize(DBUser string, DBPassword string, 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)
checkError(err)
app.Router = mux.NewRouter().StrictSlash(true)
app.handleRoute()
return nil
}
func (app *App) Run(address string) {
log.Fatal(http.ListenAndServe(address, app.Router))
}
func sendResponse(w http.ResponseWriter, statusCode int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-type", "application/json")
w.WriteHeader(statusCode)
w.Write(response)
}
func sendError(w http.ResponseWriter, statusCode int, err string) {
error_message := map[string]string{"error": err}
sendResponse(w, statusCode, error_message)
}
func (app *App) getProducts(w http.ResponseWriter, r *http.Request) {
products, err := getProducts(app.DB)
if err != nil {
sendError(w, http.StatusInternalServerError, err.Error())
checkError(err)
}
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")
return
}
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, "Invalid request payload")
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")
return
}
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())
}
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")
return
}
var p product
p.ID = key
err = p.deleteProduct(app.DB)
if err != nil {
sendError(w, http.StatusBadRequest, err.Error())
}
sendResponse(w, http.StatusOK, map[string]string{"result": "successful deleted"})
}
// CRUD Methods
func (app *App) handleRoute() {
// POST C
app.Router.HandleFunc("/product", app.createProduct).Methods("POST")
// GET R
app.Router.HandleFunc("/products/", app.getProducts).Methods("GET")
app.Router.HandleFunc("/product/{id}", app.getProduct).Methods("GET")
// PUT U
app.Router.HandleFunc("/product/{id}", app.updateProduct).Methods("PUT")
// DELETE D
app.Router.HandleFunc("/product/{id}", app.deleteProduct).Methods("DELETE")
}