| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"io" |
| 6 |
"log" |
| 7 |
. "net/http" |
| 8 |
"time" |
| 9 |
|
| 10 |
"github.com/elazarl/goproxy" |
| 11 |
goproxy_html "github.com/elazarl/goproxy/ext/html" |
| 12 |
) |
| 13 |
|
| 14 |
type Count struct { |
| 15 |
Id string |
| 16 |
Count int64 |
| 17 |
} |
| 18 |
type CountReadCloser struct { |
| 19 |
Id string |
| 20 |
R io.ReadCloser |
| 21 |
ch chan<- Count |
| 22 |
nr int64 |
| 23 |
} |
| 24 |
|
| 25 |
func (c *CountReadCloser) Read(b []byte) (n int, err error) { |
| 26 |
n, err = c.R.Read(b) |
| 27 |
c.nr += int64(n) |
| 28 |
return |
| 29 |
} |
| 30 |
func (c CountReadCloser) Close() error { |
| 31 |
c.ch <- Count{c.Id, c.nr} |
| 32 |
return c.R.Close() |
| 33 |
} |
| 34 |
|
| 35 |
func main() { |
| 36 |
proxy := goproxy.NewProxyHttpServer() |
| 37 |
timer := make(chan bool) |
| 38 |
ch := make(chan Count, 10) |
| 39 |
go func() { |
| 40 |
for { |
| 41 |
time.Sleep(20 * time.Second) |
| 42 |
timer <- true |
| 43 |
} |
| 44 |
}() |
| 45 |
go func() { |
| 46 |
m := make(map[string]int64) |
| 47 |
for { |
| 48 |
select { |
| 49 |
case c := <-ch: |
| 50 |
m[c.Id] = m[c.Id] + c.Count |
| 51 |
case <-timer: |
| 52 |
fmt.Printf("statistics\n") |
| 53 |
for k, v := range m { |
| 54 |
fmt.Printf("%s -> %d\n", k, v) |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
}() |
| 59 |
|
| 60 |
// IsWebRelatedText filters on html/javascript/css resources |
| 61 |
proxy.OnResponse(goproxy_html.IsWebRelatedText).DoFunc(func(resp *Response, ctx *goproxy.ProxyCtx) *Response { |
| 62 |
resp.Body = &CountReadCloser{ctx.Req.URL.String(), resp.Body, ch, 0} |
| 63 |
return resp |
| 64 |
}) |
| 65 |
fmt.Printf("listening on :8080\n") |
| 66 |
log.Fatal(ListenAndServe(":8080", proxy)) |
| 67 |
} |