-
Notifications
You must be signed in to change notification settings - Fork 0
/
applic.go
210 lines (171 loc) · 4.95 KB
/
applic.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// applic.go
package main
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/go-chi/chi"
_ "github.com/lib/pq"
"log"
"net/http"
"strconv"
"time"
)
// App.
type App struct {
Router *chi.Mux
DB *sql.DB
}
// Initialize create a database connection
func (a *App) Initialize() {
fmt.Println(">< Initializing... ><")
connectionString := fmt.Sprintf("postgres://postgres:password@postgres/postgres?sslmode=disable") //DB configuration lies in dbConfig file
var err error
a.DB, err = sql.Open("postgres", connectionString)
if err != nil {
log.Fatal(err)
}
fmt.Println(">< DB initialized ><")
for i := 0; i < 5; i++ {
time.Sleep(time.Duration(i) * time.Second)
if err = a.DB.Ping(); err == nil {
break
}
log.Println(err)
}
if err != nil {
log.Fatal(err)
}
a.Router = chi.NewRouter() //Creating and initializing Router
a.initializeRoutes()
fmt.Println(">< Routes initialized ><")
}
// Run simply starts the application.
func (a *App) Run(addr string) {
log.Fatal(http.ListenAndServe(":8080", a.Router))
}
//Setting paths
func (a *App) initializeRoutes() {
a.Router.Get("/employees", a.getEmployees)
a.Router.Post("/employee", a.createEmployee)
a.Router.Get("/employee/{uid:[0-9]+}", a.getEmployee)
a.Router.Put("/employee/{uid:[0-9]+}", a.updateEmployee)
a.Router.Delete("/employee/{uid:[0-9]+}", a.deleteEmployee)
}
func (a *App) getEmployee(w http.ResponseWriter, r *http.Request) {
uid, err := strconv.Atoi(chi.URLParam(r, "uid"))
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid employee ID")
return
}
p := employee{Uid: uid}
if err := p.getEmployee(a.DB); err != nil {
switch err {
case sql.ErrNoRows:
respondWithError(w, http.StatusNotFound, "employee not found")
default:
respondWithError(w, http.StatusInternalServerError, err.Error())
}
return
}
fmt.Println(">< Reading employee`s data is successful ><")
respondWithJSON(w, http.StatusOK, p)
}
func (a *App) getEmployees(w http.ResponseWriter, r *http.Request) {
count, _ := strconv.Atoi(r.FormValue("count"))
start, _ := strconv.Atoi(r.FormValue("start"))
if count > 10 || count < 1 {
count = 10
}
if start < 0 {
start = 0
}
employees, err := getEmployees(a.DB, start, count)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
/*employee1 := employee{}
for _, value := range employees {
employee1 = value
err := json.NewDecoder(r.Body).Decode(&employee1)
if err != nil{
panic(err)
}
employeeJson, err := json.Marshal(employee1)
if err != nil{
panic(err)
}
//Set Content-Type header so that clients will know how to read response
w.Header().Set("Content-Type","application/json")
w.WriteHeader(http.StatusOK)
//Write json response back to response
w.Write(employeeJson)
}*/
fmt.Println(">< Reading employees` data is successful ><")
respondWithJSON(w, http.StatusOK, employees)
}
func (a *App) createEmployee(w http.ResponseWriter, r *http.Request) {
var p employee
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&p); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
defer r.Body.Close()
if err := p.createEmployee(a.DB); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
fmt.Println(">< Employee`s profile is created ><")
respondWithJSON(w, http.StatusCreated, p)
}
func (a *App) updateEmployee(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(chi.URLParam(r, "uid"))
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid employee ID")
return
}
var p employee
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&p); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid resquest payload")
return
}
defer r.Body.Close()
p.Uid = id
if err := p.updateEmployee(a.DB); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
fmt.Println(">< Employee data ( uid - " + string(id) + " ) are updated. ><")
respondWithJSON(w, http.StatusOK, p)
}
func (a *App) deleteEmployee(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(chi.URLParam(r, "uid"))
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid employee ID")
return
}
p := employee{Uid: id}
if err := p.deleteEmployee(a.DB); err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
fmt.Println(">< Employee data ( uid - " + string(id) + " ) are deleted. ><")
respondWithJSON(w, http.StatusOK, map[string]string{"result": "success"})
}
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 checkErr(err error) {
if err != nil {
panic(err)
}
}