Skip to content

timeout middleware wraps the request context with a timeout #421

@yao560909

Description

@yao560909

func timeoutMiddleware(timeout time.Duration) func(c *gin.Context) {
return func(c *gin.Context) {
// 若无自定义超时设置,默认设置超时
_, ok := c.Request.Context().Deadline()
if ok {
c.Next()
return
}

	// wrap the request context with a timeout
	ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
	defer func() {
		// check if context timeout was reached
		if ctx.Err() == context.DeadlineExceeded {

			// write response and abort the request
			c.Writer.WriteHeader(http.StatusGatewayTimeout)
			c.Abort()
		}

		// cancel to clear resources after finished
		cancel()
	}()

	// replace request with context wrapped request
	c.Request = c.Request.WithContext(ctx)
	c.Next()
}

}这个中间件是先c.Next()再进入defer func(),c.Writer.WriteHeader(http.StatusGatewayTimeout)还有意义吗,为什么不监听超时呢

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions