Advertisement
Guest User

Untitled

a guest
Nov 1st, 2019
1,166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "time"
  5.  
  6. "github.com/gin-gonic/gin"
  7. )
  8.  
  9. func main() {
  10. Port := ":8080"
  11. route := gin.Default()
  12.  
  13. v1 := route.Group("/api")
  14.  
  15. v1.Use(
  16. timeoutFilterV3(1 * time.Second),
  17. )
  18. {
  19. v1.GET("/testTimeoutFilter", testTimeoutFilter)
  20. }
  21.  
  22. route.Run(Port)
  23. }
  24.  
  25. func testTimeoutFilter(ctx *gin.Context) {
  26.  
  27. time.Sleep(3 * time.Second)
  28. ctx.JSON(200, "ok")
  29. }
  30.  
  31. func timeoutFilterV3(t time.Duration) func(c *gin.Context) {
  32. return func(c *gin.Context) {
  33. finish := make(chan struct{})
  34.  
  35. go func() {
  36. defer func() {
  37. if err := recover(); err != nil {
  38. c.JSON(500, "error")
  39. c.Abort()
  40. finish <- struct{}{}
  41. }
  42. }()
  43. c.Next()
  44. finish <- struct{}{}
  45. }()
  46.  
  47. select {
  48. case <-time.After(t):
  49. c.JSON(504, "timeout")
  50. c.Abort()
  51. case <-finish:
  52. }
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement