forked from ulule/limiter
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"log" | ||
"net/http" | ||
|
||
"github.com/go-chi/chi" | ||
redis "github.com/go-redis/redis" | ||
"github.com/ulule/limiter" | ||
"github.com/ulule/limiter/drivers/middleware/stdlib" | ||
sredis "github.com/ulule/limiter/drivers/store/redis" | ||
) | ||
|
||
func main() { | ||
|
||
// Define a limit rate to 4 requests per hour. | ||
rate, err := limiter.NewRateFromFormatted("4-H") | ||
if err != nil { | ||
log.Fatal(err) | ||
return | ||
} | ||
|
||
// Create a redis client. | ||
option, err := redis.ParseURL("redis://localhost:6379/0") | ||
if err != nil { | ||
log.Fatal(err) | ||
return | ||
} | ||
client := redis.NewClient(option) | ||
|
||
// Create a store with the redis client. | ||
store, err := sredis.NewStoreWithOptions(client, limiter.StoreOptions{ | ||
Prefix: "limiter_chi_example", | ||
MaxRetry: 3, | ||
}) | ||
if err != nil { | ||
log.Fatal(err) | ||
return | ||
} | ||
|
||
// Create a new middleware with the limiter instance. | ||
middleware := stdlib.NewMiddleware(limiter.New(store, rate), stdlib.WithForwardHeader(true)) | ||
|
||
// Launch a simple chi server. | ||
router := chi.NewRouter() | ||
router.Use(middleware.Handler) | ||
router.Get("/", index) | ||
fmt.Println("Server is running on port 7777...") | ||
log.Fatal(http.ListenAndServe(":7777", router)) | ||
} | ||
|
||
func index(w http.ResponseWriter, r *http.Request) { | ||
w.Header().Set("Content-Type", "application/json; charset=utf-8") | ||
w.Write([]byte(`{"message": "ok"}`)) | ||
} |