Create file server basic
parent
9ad7bccbc0
commit
3f2d0644f1
|
|
@ -1,2 +1,4 @@
|
|||
**/*.sw*
|
||||
**/*.pdf
|
||||
resume
|
||||
**/*.tar
|
||||
|
|
|
|||
|
|
@ -0,0 +1,37 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"local/args"
|
||||
"local/gziphttp"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
func main() {
|
||||
as := args.NewArgSet()
|
||||
|
||||
as.Append(args.INT, "port", "port to listen on", 8080)
|
||||
as.Append(args.STRING, "root", "root dir to serve", "./public")
|
||||
as.Append(args.INT, "rps", "rate limit in requests per second", 3)
|
||||
|
||||
if err := as.Parse(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
s := http.FileServer(http.Dir(as.GetString("root")))
|
||||
limiter := rate.NewLimiter(rate.Limit(as.GetInt("rps")), as.GetInt("rps"))
|
||||
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", as.GetInt("port")), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if gziphttp.Can(r) {
|
||||
gz := gziphttp.New(w)
|
||||
w = gz
|
||||
}
|
||||
if err := limiter.Wait(r.Context()); err != nil {
|
||||
log.Println("rate limited:", err)
|
||||
return
|
||||
}
|
||||
s.ServeHTTP(w, r)
|
||||
})))
|
||||
}
|
||||
Loading…
Reference in New Issue