-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtracker.go
152 lines (131 loc) · 3.44 KB
/
tracker.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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"math/rand"
"net/http"
"os"
"time"
"github.com/gorilla/mux"
_ "github.com/mattn/go-sqlite3"
)
type visit struct {
Visitor string
Time time.Time
}
func randomString(n int) string {
letters := []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func checkError(err error) {
if err == nil {
return
}
fmt.Printf("error: %s\n", err.Error())
os.Exit(1)
}
var database *sql.DB
func initDatabase() {
var err error = nil
database, err = sql.Open("sqlite3", "./tracker.db")
checkError(err)
statement, err := database.Prepare("CREATE TABLE IF NOT EXISTS visits (tracker TEXT, visitor TEXT, time DATETIME DEFAULT CURRENT_TIMESTAMP);")
checkError(err)
_, err = statement.Exec()
checkError(err)
}
func getVisitsCount(tracker string) int {
count := 0
rows, err := database.Query("SELECT COUNT(*) FROM visits WHERE tracker = ?;", tracker)
checkError(err)
rows.Next()
err = rows.Scan(&count)
checkError(err)
err = rows.Close()
checkError(err)
return count
}
func addVisit(tracker string, visitor string) {
statement, err := database.Prepare("INSERT INTO visits (tracker, visitor) VALUES (?, ?)")
checkError(err)
_, err = statement.Exec(tracker, visitor)
checkError(err)
}
func getVisits(tracker string) []visit {
count := getVisitsCount(tracker)
if count == 0 {
fmt.Print("Baaad\n")
os.Exit(1)
}
visits := make([]visit, count)
rows, err := database.Query("SELECT * FROM visits WHERE tracker = ?;", tracker)
defer rows.Close()
checkError(err)
i := 0
for rows.Next() {
var ignore string
rows.Scan(&ignore, &visits[i].Visitor, &visits[i].Time)
i++
}
return visits
}
func createTracker() string {
tracker := randomString(50)
for getVisitsCount(tracker) != 0 {
tracker = randomString(50)
}
addVisit(tracker, "-1.-1.-1.-1")
return tracker
}
func httpVisits(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
tracker := vars["tracker"]
if getVisitsCount(tracker) == 0 {
w.WriteHeader(404)
} else {
w.WriteHeader(200)
visits := getVisits(tracker)
bytes, _ := json.Marshal(visits)
w.Write(bytes)
}
}
func httpCreate(w http.ResponseWriter, r *http.Request) {
tracker := createTracker()
w.WriteHeader(200)
bytes, _ := json.Marshal(tracker)
w.Write(bytes)
}
func httpTrack(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
tracker := vars["tracker"]
if getVisitsCount(tracker) == 0 {
w.WriteHeader(404)
} else {
ip := r.RemoteAddr
forwarded := r.Header.Get("X-FORWARDED-FOR")
if forwarded != "" {
ip = forwarded
}
addVisit(tracker, ip)
w.WriteHeader(200)
}
}
func main() {
// seed
rand.Seed(time.Now().UnixNano())
//database
initDatabase()
defer database.Close()
//router
router := mux.NewRouter()
router.HandleFunc("/visits/{tracker:[0-9a-zA-Z]+}", httpVisits)
router.HandleFunc("/track/{tracker:[0-9a-zA-Z]+}", httpTrack)
router.HandleFunc("/create", httpCreate)
http.Handle("/", router)
http.ListenAndServe(":3000", nil)
}