-
Notifications
You must be signed in to change notification settings - Fork 12
/
hits.go
69 lines (62 loc) · 1.4 KB
/
hits.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
package main
import (
"errors"
"log"
"net/http"
"path"
"time"
)
// Wrap a http.FileSystem to log how many hits it gets every given period.
type hitLoggingFsys struct {
fsImpl http.FileSystem
hitc chan string
period time.Duration
periodTicker *time.Ticker
serveDirectoryListings bool
}
func newHitLoggingFsys(
fsImpl http.FileSystem,
period time.Duration,
serveDirectoryListings bool) *hitLoggingFsys {
h := hitLoggingFsys{
fsImpl: fsImpl,
hitc: make(chan string),
period: period,
serveDirectoryListings: serveDirectoryListings,
}
h.periodTicker = time.NewTicker(h.period)
go h.runLoop()
return &h
}
func (h *hitLoggingFsys) Open(name string) (http.File, error) {
h.hitc <- name
f, err := h.fsImpl.Open(name)
if err != nil {
return nil, err
}
if !h.serveDirectoryListings {
stat, err := f.Stat()
if err != nil {
return nil, err
}
if stat.IsDir() {
return nil, errors.New("directory listing has been disallowed")
}
}
return f, nil
}
func (h *hitLoggingFsys) runLoop() {
for {
hits := make(map[string]uint) // resource "directory" -> hit count
ThisPeriod:
for {
select {
case resource := <-h.hitc:
hits[path.Dir(resource)]++
case <-h.periodTicker.C:
log.Printf("Hits in last %v period by dir: %v", h.period, hits)
break ThisPeriod
}
}
}
}