add dldcounter to valid ip address

This commit is contained in:
gzliuxin
2018-11-26 15:05:59 +08:00
parent b81894b0cf
commit 1f68fcb45f
2 changed files with 31 additions and 2 deletions

21
db.go
View File

@@ -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)

View File

@@ -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)
}
}