-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuserStatusHandler.go
More file actions
63 lines (49 loc) · 1.67 KB
/
userStatusHandler.go
File metadata and controls
63 lines (49 loc) · 1.67 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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
)
func userStatusHandler(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
req := struct {
APIToken string `json:"api_token"`
Status string `json:"status"`
}{"", ""}
err := decoder.Decode(&req)
if err != nil {
failWithStatusCode(err, http.StatusText(http.StatusBadRequest), w, http.StatusBadRequest)
return
}
switch r.Method {
case "GET":
result := ""
queryString := "SELECT current_status FROM users WHERE api_token LIKE $1;"
stmt, _ := db.Prepare(queryString)
err = stmt.QueryRow(req.APIToken).Scan(&result)
if err == sql.ErrNoRows {
failWithStatusCode(err, "could not find user", w, http.StatusNotFound)
return
} else if err != nil {
failWithStatusCode(err, "failed to query database", w, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "{\"user_status\":\"%s\"}", result)
case "POST":
queryString := "UPDATE users SET current_status = $1 WHERE api_token LIKE $2;"
stmt, _ := db.Prepare(queryString)
res, err := stmt.Exec(req.Status, req.APIToken)
if err != nil {
failWithStatusCode(err, "failed to query database", w, http.StatusInternalServerError)
return
}
numRows, err := res.RowsAffected()
if numRows < 1 {
failWithStatusCode(err, "could not find user", w, http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
}
}