-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
311 lines (275 loc) · 8.69 KB
/
main.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
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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"strings"
_ "github.com/mattn/go-sqlite3"
)
type Visitor struct {
IP string
Latitude float64
Longitude float64
City string
Country string
}
var db *sql.DB
func main() {
var err error
db, err = sql.Open("sqlite3", "./db/database.sqlite")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Create table if it does not exist
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS visitors (
ip TEXT PRIMARY KEY,
latitude REAL,
longitude REAL,
city TEXT,
country TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)`)
if err != nil {
log.Fatal(err)
}
// Add missing columns if necessary
addColumnIfNotExists("city", "TEXT")
addColumnIfNotExists("country", "TEXT")
addColumnIfNotExists("timestamp", "DATETIME DEFAULT CURRENT_TIMESTAMP")
// Serve static files
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
// Routes
http.HandleFunc("/", indexHandler)
http.HandleFunc("/stats", statsPageHandler)
http.HandleFunc("/api/visitors", apiVisitorsHandler)
http.HandleFunc("/api/stats", apiStatsHandler)
http.HandleFunc("/api/statistics", apiStatisticsHandler)
http.HandleFunc("/api/visitor_types", apiVisitorTypesHandler)
http.HandleFunc("/api/trends", apiTrendsHandler)
port := os.Getenv("GO_MAP_PORT")
if port == "" {
port = "8905" // Default port if not specified
}
log.Printf("Starting server on :%s...\n", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
// Helper function to add columns if they don't exist
func addColumnIfNotExists(columnName string, columnType string) {
query := fmt.Sprintf("PRAGMA table_info(visitors)")
rows, err := db.Query(query)
if err != nil {
log.Printf("Error querying table info: %v\n", err)
return
}
defer rows.Close()
columnExists := false
for rows.Next() {
var colID int
var name, dataType string
var notNull, pk int
var dfltValue sql.NullString
if err := rows.Scan(&colID, &name, &dataType, ¬Null, &dfltValue, &pk); err != nil {
log.Printf("Error scanning table info: %v\n", err)
return
}
if name == columnName {
columnExists = true
break
}
}
if !columnExists {
query = fmt.Sprintf("ALTER TABLE visitors ADD COLUMN %s %s", columnName, columnType)
_, err := db.Exec(query)
if err != nil {
log.Printf("Error adding column %s: %v\n", columnName, err)
}
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("templates/index.html")
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
tmpl.Execute(w, nil)
ip := getRealIP(r)
if ip == "" {
log.Println("Failed to extract IP")
return
}
log.Printf("Visitor IP: %s\n", ip)
latitude, longitude, city, country := fetchGeolocationFromIPInfo(ip)
log.Printf("Inserting into DB: IP %s, Latitude %f, Longitude %f, City %s, Country %s\n", ip, latitude, longitude, city, country)
_, err = db.Exec(`INSERT OR IGNORE INTO visitors (ip, latitude, longitude, city, country) VALUES (?, ?, ?, ?, ?)`, ip, latitude, longitude, city, country)
if err != nil {
log.Printf("Error inserting into DB: %v\n", err)
}
}
func statsPageHandler(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("templates/stats.html")
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
tmpl.Execute(w, nil)
}
func apiVisitorsHandler(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(`SELECT ip, latitude, longitude, city, country FROM visitors`)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer rows.Close()
var visitors []Visitor
for rows.Next() {
var visitor Visitor
if err := rows.Scan(&visitor.IP, &visitor.Latitude, &visitor.Longitude, &visitor.City, &visitor.Country); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
visitors = append(visitors, visitor)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(visitors)
}
func apiStatsHandler(w http.ResponseWriter, r *http.Request) {
var unique int
err := db.QueryRow(`SELECT COUNT(DISTINCT ip) FROM visitors`).Scan(&unique)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
log.Printf("Error querying unique visitor count: %v\n", err)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]int{
"unique_visitors": unique,
})
}
func apiStatisticsHandler(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(`SELECT country, COUNT(*) as count FROM visitors GROUP BY country`)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
log.Printf("Error querying statistics: %v\n", err)
return
}
defer rows.Close()
var labels []string
var counts []int
for rows.Next() {
var country string
var count int
if err := rows.Scan(&country, &count); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
labels = append(labels, country)
counts = append(counts, count)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"labels": labels,
"counts": counts,
})
}
func apiVisitorTypesHandler(w http.ResponseWriter, r *http.Request) {
var unique, returning int
err := db.QueryRow(`SELECT COUNT(DISTINCT ip) FROM visitors`).Scan(&unique)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
err = db.QueryRow(`SELECT COUNT(ip) - COUNT(DISTINCT ip) FROM visitors`).Scan(&returning)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]int{
"unique_visitors": unique,
"returning_visitors": returning,
})
}
func apiTrendsHandler(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(`SELECT DATE(timestamp) as date, COUNT(*) as count FROM visitors GROUP BY DATE(timestamp) ORDER BY date`)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer rows.Close()
var dates []string
var visitorCounts []int
for rows.Next() {
var date string
var count int
if err := rows.Scan(&date, &count); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
dates = append(dates, date)
visitorCounts = append(visitorCounts, count)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"dates": dates,
"visitor_counts": visitorCounts,
})
}
func getRealIP(r *http.Request) string {
ip := r.Header.Get("CF-Connecting-IP")
if ip == "" {
ip = r.Header.Get("X-Forwarded-For")
}
if ip == "" {
ip = strings.Split(r.RemoteAddr, ":")[0]
}
log.Printf("Extracted IP: %s\n", ip)
return ip
}
func fetchGeolocationFromIPInfo(ip string) (float64, float64, string, string) {
if ip == "" || ip == "127.0.0.1" {
log.Println("Using default location for invalid IP")
return 37.7749, -122.4194, "San Francisco", "United States"
}
token := os.Getenv("IPINFO_TOKEN")
if token == "" {
log.Println("IPINFO_TOKEN environment variable not set")
return 37.7749, -122.4194, "San Francisco", "United States"
}
url := fmt.Sprintf("https://ipinfo.io/%s?token=%s", ip, token)
resp, err := http.Get(url)
if err != nil {
log.Printf("Failed to fetch geolocation for IP %s: %v\n", ip, err)
return 37.7749, -122.4194, "San Francisco", "United States"
}
defer resp.Body.Close()
var result struct {
Loc string `json:"loc"`
City string `json:"city"`
Country string `json:"country"`
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("Failed to read response body for IP %s: %v\n", ip, err)
return 37.7749, -122.4194, "San Francisco", "United States"
}
if err := json.Unmarshal(body, &result); err != nil {
log.Printf("Failed to parse geolocation response for IP %s: %v\n", ip, err)
return 37.7749, -122.4194, "San Francisco", "United States"
}
locParts := strings.Split(result.Loc, ",")
if len(locParts) != 2 {
log.Printf("Invalid location format for IP %s: %s\n", ip, result.Loc)
return 37.7749, -122.4194, "San Francisco", "United States"
}
var latitude, longitude float64
fmt.Sscanf(locParts[0], "%f", &latitude)
fmt.Sscanf(locParts[1], "%f", &longitude)
log.Printf("Geolocation for IP %s: Latitude %f, Longitude %f, City %s, Country %s\n", ip, latitude, longitude, result.City, result.Country)
return latitude, longitude, result.City, result.Country
}