package cmd import ( "github.com/gorilla/mux" "github.com/spf13/cobra" "github.com/throttled/throttled" "github.com/throttled/throttled/store/memstore" "log" "mazeratsgen/internal/handlers" "net/http" ) var serverCmd = &cobra.Command{ Use: "server", Short: "Create a web server with REST API", Run: startServer, } func init() { rootCmd.AddCommand(serverCmd) } func startServer(cmd *cobra.Command, args []string) { r := mux.NewRouter() handlers.LoadHandlers(r) r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("web/swagger")))) r.Use(loggingMiddleware) log.Printf("Starting web server on 0.0.0.0:8080") store, err := memstore.New(65536) if err != nil { log.Fatal(err) } // Maximum burst of 30 which refills at 5 tokens per minute. quota := throttled.RateQuota{MaxRate: throttled.PerMin(30), MaxBurst: 5} rateLimiter, err := throttled.NewGCRARateLimiter(store, quota) if err != nil { log.Fatal(err) } httpRateLimiter := throttled.HTTPRateLimiter{ RateLimiter: rateLimiter, VaryBy: &throttled.VaryBy{Path: true}, } log.Fatal(http.ListenAndServe(":8080", httpRateLimiter.RateLimit(r))) } func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf( "%s %s %s %s", r.RemoteAddr, r.Method, r.URL, r.Header["User-Agent"], ) next.ServeHTTP(w, r) }) }