-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
226 lines (191 loc) · 5.27 KB
/
main.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package main
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
"log"
"net/http"
"time"
)
// StudentID represents a ...
// swagger:parameters getStudent
type StudentID struct {
// The ID of the student
//
// in: path
// required: true
ID string `json:"id"`
}
// CourseID represents a ...
// swagger:parameters getCourse
type CourseID struct {
// The ID of the course
//
// in: path
// required: true
ID string `json:"id"`
}
// Student represents a ...
// swagger:response StudentResponse
type Student struct {
// in: path
// required: true
ID string `json:"id"`
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
Email string `json:"email"`
}
// Course represents a ...
// swagger:response CourseResponse
type Course struct {
ID string `json:"id"`
Title string `json:"title"`
}
// HomeRouterHandler represents a ...
func HomeRouterHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, http.StatusOK)
log.Printf("%v GET '%s'\n", http.StatusOK, r.URL.Path)
}
// APIRouterHealthHandler represents a ...
func APIRouterHealthHandler(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]bool{"ok": true})
}
// getStudents represents a ...
func getStudents(w http.ResponseWriter, r *http.Request) {
// swagger:route GET /api/v2/students students getStudents
// responses:
// 200: StudentResponse
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(readStudents())
}
// getStudent represents a ...
func getStudent(w http.ResponseWriter, r *http.Request) {
// swagger:route GET /api/v2/students/{id} students getStudent
// responses:
// 200: StudentResponse
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for _, item := range readStudents() {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&Student{})
}
// getCourses represents a ...
func getCourses(w http.ResponseWriter, r *http.Request) {
// swagger:route GET /api/v2/courses courses getCourses
// responses:
// 200: CourseResponse
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(readCourses())
}
// getCourse represents a ...
func getCourse(w http.ResponseWriter, r *http.Request) {
// swagger:route GET /api/v2/courses/{id} courses getCourse
// responses:
// 200: CourseResponse
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for _, item := range readCourses() {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
json.NewEncoder(w).Encode(&Course{})
}
func createStudent(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
s := Student{}
_ = json.NewDecoder(r.Body).Decode(&s)
fmt.Println(json.NewEncoder(w).Encode(s))
conn := NewDbConn()
connStr := fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable", conn.DbHost, conn.DbUsername, conn.DbPassword, conn.DbName)
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.Query(fmt.Sprintf("INSERT INTO students (firstname, lastname, email) VALUES ('%s', '%s', '%s');", s.Firstname, s.Lastname, s.Email))
if err != nil {
log.Fatal(err)
}
defer rows.Close()
}
func readStudents() []Student {
conn := NewDbConn()
connStr := fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable", conn.DbHost, conn.DbUsername, conn.DbPassword, conn.DbName)
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.Query("SELECT * FROM students;")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
students := []Student{}
for rows.Next() {
s := Student{}
err := rows.Scan(&s.ID, &s.Firstname, &s.Lastname, &s.Email)
if err != nil {
log.Fatal("rows.Scan: ", err)
}
students = append(students, s)
}
return students
}
func readCourses() []Course {
conn := NewDbConn()
connStr := fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable", conn.DbHost, conn.DbUsername, conn.DbPassword, conn.DbName)
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, err := db.Query("SELECT * FROM courses;")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
courses := []Course{}
for rows.Next() {
c := Course{}
err := rows.Scan(&c.ID, &c.Title)
if err != nil {
log.Fatal("rows.Scan: ", err)
}
courses = append(courses, c)
}
return courses
}
func init() {
err := godotenv.Load()
if err != nil {
log.Print("Error loading .env file")
}
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", HomeRouterHandler)
r.HandleFunc("/api/v2/health", APIRouterHealthHandler).Methods("GET")
r.HandleFunc("/api/v2/students", getStudents).Methods("GET")
r.HandleFunc("/api/v2/students/{id}", getStudent).Methods("GET")
r.HandleFunc("/api/v2/students", createStudent).Methods("POST")
r.HandleFunc("/api/v2/courses", getCourses).Methods("GET")
r.HandleFunc("/api/v2/courses/{id}", getCourse).Methods("GET")
http.Handle("/", r)
srv := &http.Server{
Handler: r,
Addr: ":80",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}