Create file server basic

master
bel 2020-09-13 20:19:59 -06:00
parent 9ad7bccbc0
commit 3f2d0644f1
2 changed files with 39 additions and 0 deletions

2
.gitignore vendored
View File

@ -1,2 +1,4 @@
**/*.sw* **/*.sw*
**/*.pdf **/*.pdf
resume
**/*.tar

37
main.go Normal file
View File

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