Repository navigation
Expand file tree
/
Copy pathsat.go
More file actions
326 lines (271 loc) · 9.07 KB
/
Copy pathsat.go
File metadata and controls
326 lines (271 loc) · 9.07 KB
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
_ "github.com/mattn/go-sqlite3"
)
// JSON struct to hold question details
type QuestionDetails struct {
QuestionID string `json:"questionId"`
ID string `json:"id"`
Test string `json:"test"`
Category string `json:"category"`
Domain string `json:"domain"`
Skill string `json:"skill"`
Difficulty string `json:"difficulty"`
Details string `json:"details"`
Question string `json:"question"`
AnswerChoices string `json:"answerChoices"`
Answer string `json:"answer"`
Rationale string `json:"rationale"`
}
type SATQuestion struct {
Test string `json:"test"`
Difficulty []string `json:"difficulty"`
Subdomain []string `json:"subdomain"`
}
type Register struct {
Email string `json:"email"`
Password string `json:"password"`
}
func indexSat(w http.ResponseWriter, r *http.Request) {
// load index.html from static/
http.ServeFile(w, r, "./static/sat/pages/practice.html")
}
func findQuestions(w http.ResponseWriter, r *http.Request, test, category, domain, skill, difficulty string) {
var err error
// Build the query with filters
query := `
SELECT questionId
FROM sat_questions
WHERE test = ?
AND category = ?
AND domain = ?
AND skill = ?
AND difficulty = ?`
// Execute the query with user inputs as filters
rows, err := db.Query(query, test, category, domain, skill, difficulty)
if err != nil {
http.Error(w, "Failed to query database", http.StatusInternalServerError)
return
}
defer rows.Close()
// Collect matching question IDs
var questionId string
matchingQuestions := []string{}
for rows.Next() {
err := rows.Scan(&questionId)
if err != nil {
log.Fatal(err)
}
matchingQuestions = append(matchingQuestions, questionId)
}
if len(matchingQuestions) > 0 {
viewQuestionDetails(w, matchingQuestions)
} else {
fmt.Fprintln(w, `<html><body>No questions found matching the filters.</body></html>`)
}
}
// viewQuestionDetails handles displaying all information for each questionId in matchingQuestions
func viewQuestionDetails(w http.ResponseWriter, matchingQuestions []string) {
var err error
// Slice to store details of all matching questions
var questions []QuestionDetails
for _, questionId := range matchingQuestions {
queryDetails := `
SELECT questionId, id, test, category, domain, skill, difficulty, details,
question, answer_choices, answer, rationale
FROM sat_questions
WHERE questionId = ?`
// Stores question details
var question QuestionDetails
// Execute the query and scan the result into the struct
err = db.QueryRow(queryDetails, questionId).Scan(
&question.QuestionID, &question.ID, &question.Test, &question.Category, &question.Domain,
&question.Skill, &question.Difficulty, &question.Details, &question.Question,
&question.AnswerChoices, &question.Answer, &question.Rationale,
)
if err != nil {
if err == sql.ErrNoRows {
log.Printf("No question found with ID: %s", questionId)
continue
} else {
log.Printf("Error querying the database for questionId %s: %v", questionId, err)
http.Error(w, "Error querying the database", http.StatusInternalServerError)
return
}
}
// Append the question details to the slice
questions = append(questions, question)
}
// Convert the slice of questions to a JSON string
jsonData, err := json.Marshal(questions)
if err != nil {
log.Printf("Error converting questions to JSON: %v", err)
http.Error(w, "Error generating JSON response", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func ServeForm(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `
<html>
<body>
<h1>Find Questions</h1>
<form action="/sat/find-questions" method="post">
Test: <input type="text" name="test"><br>
Category: <input type="text" name="category"><br>
Domain: <input type="text" name="domain"><br>
Skill: <input type="text" name="skill"><br>
Difficulty: <input type="text" name="difficulty"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
`)
}
// Handle form submission and call findQuestions
func FindQuestionsHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
// Extract form values
test := r.FormValue("test")
category := r.FormValue("category")
domain := r.FormValue("domain")
skill := r.FormValue("skill")
difficulty := r.FormValue("difficulty")
// Call the findQuestions function with the provided inputs
findQuestions(w, r, test, category, domain, skill, difficulty)
} else {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}
}
func FindQuestionsHandlerv2(w http.ResponseWriter, r *http.Request) {
// parse JSON in the form of
// {
// "test": "SAT",
// "difficulty": ["Medium", "Hard"],
// "subdomains": ["Information and Ideas", "Algebra"]
// }
// parse json
var data SATQuestion
// Check if the body is empty first
if r.Body == nil || r.ContentLength == 0 {
http.Error(w, "Request body is empty", http.StatusBadRequest)
return
}
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
// return 400 bad request
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
query := `
SELECT questionId, id, test, category, domain, skill, difficulty, details,
question, answer_choices, answer, rationale
FROM sat_questions
WHERE test = ?
`
args := []interface{}{}
args = append(args, data.Test)
query += " AND difficulty IN ("
difficultyPlaceholders := []string{}
for _, item := range data.Difficulty {
difficultyPlaceholders = append(difficultyPlaceholders, "?")
args = append(args, item)
}
query += strings.Join(difficultyPlaceholders, ",") + ") AND skill IN ("
subdomainPlaceholders := []string{}
for _, item := range data.Subdomain {
subdomainPlaceholders = append(subdomainPlaceholders, "?")
args = append(args, item)
}
query += strings.Join(subdomainPlaceholders, ",") + ")"
// query the db
rows, err := db.Query(query, args...)
if err != nil {
// return http internal error
http.Error(w, "Error querying: " + err.Error(), http.StatusInternalServerError)
return
}
questions := []QuestionDetails{}
// iterate oer the rows
for rows.Next() {
var question QuestionDetails
err = rows.Scan(&question.QuestionID, &question.ID, &question.Test,
&question.Category, &question.Domain, &question.Skill,
&question.Difficulty, &question.Details, &question.Question,
&question.AnswerChoices, &question.Answer, &question.Rationale,
)
if err != nil {
// return http internal error
http.Error(w, "Error querying the database" + err.Error(), http.StatusInternalServerError)
return
}
// append the question
// make the object json and append
// convert to json
// append the json
questions = append(questions, question)
}
// return the json
jsonData, err := json.Marshal(questions)
if err != nil {
log.Printf("Error converting questions to JSON: %v", err)
http.Error(w, "Error generating JSON response", http.StatusInternalServerError)
return
}
defer rows.Close()
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func register(w http.ResponseWriter, r *http.Request) {
var data Register
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// TODO: hash password
// insert into database
_, err = db.Exec("INSERT INTO sat_users (username, password) VALUES (?, ?)", data.Email, data.Password)
if err != nil {
http.Error(w, "Error inserting into database: " + err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("User registered successfully"))
}
func initializeSat(db *sql.DB) {
// create table if not exists
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS sat_questions (
questionId TEXT PRIMARY KEY,
id TEXT,
test TEXT,
category TEXT,
domain TEXT,
skill TEXT,
difficulty TEXT,
details TEXT,
question TEXT,
answer_choices TEXT,
answer TEXT,
rationale TEXT
)`)
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS sat_users (
username TEXT PRIMARY KEY,
password TEXT
)`)
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/sat", indexSat)
http.HandleFunc("/sat/test", ServeForm)
http.HandleFunc("/sat/find-questions", FindQuestionsHandler)
http.HandleFunc("/sat/find-questions-v2", FindQuestionsHandlerv2)
http.HandleFunc("/sat/register", register)
}