forked from usefathom/fathom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sites.go
88 lines (73 loc) · 1.66 KB
/
sites.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
package api
import (
"encoding/json"
"math/rand"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/usefathom/fathom/pkg/models"
)
// seed rand pkg on program init
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
// GET /api/sites
func (api *API) GetSitesHandler(w http.ResponseWriter, r *http.Request) error {
result, err := api.database.GetSites()
if err != nil {
return err
}
return respond(w, http.StatusOK, envelope{Data: result})
}
// POST /api/sites
// POST /api/sites/{id}
func (api *API) SaveSiteHandler(w http.ResponseWriter, r *http.Request) error {
var s *models.Site
vars := mux.Vars(r)
sid, ok := vars["id"]
if ok {
id, err := strconv.ParseInt(sid, 10, 64)
if err != nil {
return err
}
s, err = api.database.GetSite(id)
if err != nil {
return err
}
} else {
s = &models.Site{
TrackingID: generateTrackingID(),
}
}
err := json.NewDecoder(r.Body).Decode(s)
if err != nil {
return err
}
if err := api.database.SaveSite(s); err != nil {
return err
}
return respond(w, http.StatusOK, envelope{Data: s})
}
// DELETE /api/sites/{id}
func (api *API) DeleteSiteHandler(w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
id, err := strconv.ParseInt(vars["id"], 10, 64)
if err != nil {
return err
}
if err := api.database.DeleteSite(&models.Site{ID: id}); err != nil {
return err
}
return respond(w, http.StatusOK, envelope{Data: true})
}
func generateTrackingID() string {
return randomString(5)
}
func randomString(len int) string {
bytes := make([]byte, len)
for i := 0; i < len; i++ {
bytes[i] = byte(65 + rand.Intn(25)) //a=65 and z = 65+25
}
return string(bytes)
}