-
Notifications
You must be signed in to change notification settings - Fork 2
/
module.go
91 lines (73 loc) · 1.91 KB
/
module.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
package main
import (
"net/http"
"strconv"
"time"
"github.com/go-chi/chi"
"github.com/jmoiron/sqlx"
)
type RawData map[string]interface{}
type ModuleData struct {
ID int `json:"id"`
Text string `json:"text"`
Name string `json:"name"`
Updated time.Time `json:"updated"`
}
type ModuleDataResponse struct {
ID int `json:"id"`
}
func bytesToString(m map[string]interface{}) {
for k, v := range m {
b, ok := v.([]byte)
if ok {
m[k] = string(b)
}
}
}
func moduleAPI(r *chi.Mux, db *sqlx.DB, dataDB *sqlx.DB) {
r.Get("/api/modules", func(w http.ResponseWriter, r *http.Request) {
temp := make([]ModuleData, 0, 0)
err := db.Select(&temp, "SELECT * FROM modules")
if err != nil {
format.Text(w, 500, err.Error())
return
}
format.JSON(w, 200, temp)
})
r.Post("/api/modules", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
name := r.Form.Get("name")
text := r.Form.Get("text")
res, err := db.Exec("INSERT INTO modules(name, text) VALUES(?, ?)", name, text)
var nid int64
if err == nil {
nid, err = res.LastInsertId()
}
if err != nil {
format.Text(w, 500, err.Error())
return
}
format.JSON(w, 200, ModuleDataResponse{int(nid)})
})
r.Put("/api/modules/{id}", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
name := r.Form.Get("name")
text := r.Form.Get("text")
_, err := db.Exec("UPDATE modules SET name = ?, text = ? WHERE id = ?", name, text, id)
if err != nil {
format.Text(w, 500, err.Error())
return
}
format.JSON(w, 200, ModuleDataResponse{id})
})
r.Delete("/api/modules/{id}", func(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
_, err := db.Exec("DELETE FROM modules WHERE id = ?", id)
if err != nil {
format.Text(w, 500, err.Error())
return
}
format.JSON(w, 200, ModuleDataResponse{id})
})
}