Advertisement
Guest User

Untitled

a guest
Nov 1st, 2019
1,051
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 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.     time.Sleep(3 * time.Second)
  27.     ctx.JSON(200, "ok")
  28. }
  29.  
  30. func timeoutFilterV3(t time.Duration) func(c *gin.Context) {
  31.     return func(c *gin.Context) {
  32.         /*finish := make(chan struct{})
  33.  
  34.         go func() {
  35.             defer func() {
  36.                 if err := recover(); err != nil {
  37.                     c.JSON(500, "error")
  38.                     c.Abort()
  39.                     finish <- struct{}{}
  40.                 }
  41.             }()
  42.             c.Next()
  43.             finish <- struct{}{}
  44.         }()*/
  45.  
  46.         select {
  47.         case <-time.After(t):
  48.             c.JSON(504, "timeout")
  49.             c.Abort()
  50.         }
  51.         c.Next()
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement