example_test.go 802 B

12345678910111213141516171819202122232425262728
  1. package rate_test
  2. import (
  3. "go-common/library/net/http/blademaster"
  4. "go-common/library/net/http/blademaster/middleware/rate"
  5. )
  6. // This example create a rate middleware instance and attach to a blademaster engine,
  7. // it will protect '/ping' API frequency with specified policy.
  8. // If any internal service who requests this API more frequently than 1 req/second,
  9. // a StatusTooManyRequests error will be raised.
  10. func Example() {
  11. lim := rate.New(&rate.Config{
  12. URLs: map[string]*rate.Limit{
  13. "/ping": &rate.Limit{Limit: 1, Burst: 2},
  14. },
  15. Apps: map[string]*rate.Limit{
  16. "a-secret-app-key": &rate.Limit{Limit: 1, Burst: 2},
  17. },
  18. })
  19. engine := blademaster.Default()
  20. engine.Use(lim)
  21. engine.GET("/ping", func(c *blademaster.Context) {
  22. c.String(200, "%s", "pong")
  23. })
  24. engine.Run(":18080")
  25. }