diff --git a/db.go b/db.go index 809fa60..28eba24 100644 --- a/db.go +++ b/db.go @@ -79,6 +79,27 @@ func (model *Model) AutoSave() bool { return false } +// DldCounter is used to validate duplicated download requests +type DldCounter struct { + IPHistory map[string]time.Time +} + +var DCounter DldCounter = DldCounter{} +var DldInterval float64 = 60.0 // seconds + +func (counter *DldCounter) Validate(ip string) bool { + if counter.IPHistory == nil { + counter.IPHistory = make(map[string]time.Time) + } + if time.Since(counter.IPHistory[ip]).Seconds() > DldInterval { + counter.IPHistory[ip] = time.Now() + // fmt.Println("valid", ip) + return true + } + // fmt.Println("invalid", ip) + return false +} + // func main() { // filename := "./mydb.json" // DBModel.DBRead(filename) diff --git a/httpstaticserver.go b/httpstaticserver.go index a0393d9..db9663a 100644 --- a/httpstaticserver.go +++ b/httpstaticserver.go @@ -10,6 +10,7 @@ import ( "io/ioutil" "log" "mime" + "net" "net/http" "net/url" "os" @@ -126,7 +127,7 @@ func (s *HTTPStaticServer) hIndex(w http.ResponseWriter, r *http.Request) { } if r.FormValue("download") == "true" { w.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(filepath.Base(path))) - s.DBModel.Incre(path) + DldIncre(s.DBModel, r.RemoteAddr, path) } http.ServeFile(w, r, relPath) } @@ -289,7 +290,7 @@ func (s *HTTPStaticServer) hInfo(w http.ResponseWriter, r *http.Request) { func (s *HTTPStaticServer) hZip(w http.ResponseWriter, r *http.Request) { path := mux.Vars(r)["path"] - s.DBModel.Incre(path) + DldIncre(s.DBModel, r.RemoteAddr, path) CompressToZip(w, filepath.Join(s.Root, path)) } @@ -766,3 +767,10 @@ func checkFilename(name string) error { } return nil } + +func DldIncre(model Model, rAddress string, path string) { + ip, _, _ := net.SplitHostPort(rAddress) + if DCounter.Validate(ip) { + model.Incre(path) + } +}