forked from ulule/limiter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
56 lines (47 loc) · 1.29 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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"}`))
}