正在用 Go 开发一个下载服务器。 我需要将用户的下载速度限制在 100KB/s。
没啥好说,直接上码
package main import ( "fmt" "net/http" "os" //"database/sql" "log" "io" "github.com/juju/ratelimit" ) var ( serverid = 1 filespath = os.Getenv("HOME") + "/PhpstormPorjects/kickfy/server/files" maxspeed = 1024*100 ) func main() { fmt.Printf("Sever has been started.n") fmt.Printf("Server ID: %vn", serverid) fmt.Printf("Files path: %vn", filespath) http.HandleFunc("/serve", serveFile) log.Fatal(http.ListenAndServe(":8080", nil)) } func serveFile(w http.ResponseWriter, r *http.Request) { fileID := r.URL.Query().Get("fileID") if len(fileID) != 0 { w.Header().Set("Content-Disposition", "attachment; filename=Wiki.png") w.Header().Set("Content-Type", r.Header.Get("Content-Type")) w.Header().Set("Content-Length", r.Header.Get("Content-Length")) file, err := os.Open("server.go") defer file.Close() if err != nil { http.NotFound(w, r) return } bucket := ratelimit.NewBucketWithRate(100*1024, 100*1024) io.Copy(w, ratelimit.Reader(file, bucket)) } else { io.WriteString(w, "Invalid request.") } } func delete_old_files () { }
发表评论 取消回复