Created
August 9, 2019 09:12
-
-
Save plutov/dc64347e0fb611c588e927bc48eb806c to your computer and use it in GitHub Desktop.
main.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"net/http" | |
) | |
var limiter = NewIPRateLimiter(1, 5) | |
func main() { | |
mux := http.NewServeMux() | |
mux.HandleFunc("/", okHandler) | |
if err := http.ListenAndServe(":8888", limitMiddleware(mux)); err != nil { | |
log.Fatalf("unable to start server: %s", err.Error()) | |
} | |
} | |
func limitMiddleware(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
limiter := limiter.GetLimiter(r.RemoteAddr) | |
if !limiter.Allow() { | |
http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests) | |
return | |
} | |
next.ServeHTTP(w, r) | |
}) | |
} | |
func okHandler(w http.ResponseWriter, r *http.Request) { | |
// Some very expensive database call | |
w.Write([]byte("alles gut")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment