/
server.go
104 lines (68 loc) · 2.05 KB
/
server.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
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/remotejob/simple_go_http_server/check_logfile_existense"
"github.com/remotejob/simple_go_http_server/domains"
"github.com/remotejob/simple_go_http_server/entryLogsHandler"
"github.com/remotejob/simple_go_http_server/recordHit"
)
const logfile = "logs.csv"
const timeSeconds int = 60
const cleanUpHitsDelta int = 10
var counterToClenUpLogfile int
var newLogsEntry *entryLogsHandler.EntryLog
var deltaTime time.Duration
func init() {
deltaTime = time.Duration(time.Second * time.Duration(timeSeconds))
newLogsEntry = entryLogsHandler.NewEntryLog()
exist := check_logfile_existense.Check(logfile)
if !exist {
log.Println("log file not exist")
file, err := os.Create(logfile)
if err != nil {
log.Fatalln(err.Error())
}
file.Close()
} else {
newLogsEntry.AddLastRecords(logfile, deltaTime, true)
}
}
func middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
now := time.Now()
log := domains.Log{now, req.UserAgent()}
go recordHit.Record(logfile, log)
h.ServeHTTP(rw, req)
})
}
func loghandler(rw http.ResponseWriter, req *http.Request) {
go newLogsEntry.AddNewHit(req.UserAgent())
var htmlLogs [][]string
for i, logentry := range newLogsEntry.EntryLog {
delta := time.Since(logentry.Date)
if deltaTime.Seconds() > delta.Seconds() {
htmlLogs = append(htmlLogs, []string{logentry.Date.Format(time.RFC3339), logentry.Log})
} else {
newLogsEntry.DeleteExtraRecords(i)
counterToClenUpLogfile++
if counterToClenUpLogfile > cleanUpHitsDelta {
newLogsEntry.AddLastRecords(logfile, deltaTime, false)
counterToClenUpLogfile = 0
}
}
}
//Show All information
fmt.Fprintln(rw, "Count", len(htmlLogs), "hits last 60 seconds")
fmt.Fprintln(rw, "-------------------------------------------------")
for i, htmlLog := range htmlLogs {
fmt.Fprintln(rw, i, htmlLog)
}
}
func main() {
h := middleware(http.HandlerFunc(loghandler))
log.Fatal(http.ListenAndServe(":8080", h))
}