gin框架timeout超时

Posted hongmingover

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了gin框架timeout超时相关的知识,希望对你有一定的参考价值。

package timeout

import (
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
)

func emptySuccessResponse(c *gin.Context) 
	time.Sleep(200 * time.Microsecond)
	c.String(http.StatusOK, "")


func TestTimeout(t *testing.T) 
	r := gin.New()
	r.GET("/", New(WithTimeout(50*time.Microsecond), WithHandler(emptySuccessResponse)))

	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	r.ServeHTTP(w, req)

	assert.Equal(t, http.StatusRequestTimeout, w.Code)
	assert.Equal(t, http.StatusText(http.StatusRequestTimeout), w.Body.String())


func TestWithoutTimeout(t *testing.T) 
	r := gin.New()
	r.GET("/", New(WithTimeout(-1*time.Microsecond), WithHandler(emptySuccessResponse)))

	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	r.ServeHTTP(w, req)

	assert.Equal(t, http.StatusOK, w.Code)
	assert.Equal(t, "", w.Body.String())


func testResponse(c *gin.Context) 
	c.String(http.StatusRequestTimeout, "test response")


func TestCustomResponse(t *testing.T) 
	r := gin.New()
	r.GET("/", New(
		WithTimeout(100*time.Microsecond),
		WithHandler(emptySuccessResponse),
		WithResponse(testResponse),
	))

	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	r.ServeHTTP(w, req)

	assert.Equal(t, http.StatusRequestTimeout, w.Code)
	assert.Equal(t, "test response", w.Body.String())


func emptySuccessResponse2(c *gin.Context) 
	time.Sleep(50 * time.Microsecond)
	c.String(http.StatusOK, "")

func TestSuccess(t *testing.T) 
	r := gin.New()
	r.GET("/", New(
		WithTimeout(1*time.Second),
		WithHandler(emptySuccessResponse2),
		WithResponse(testResponse),
	))

	w := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	r.ServeHTTP(w, req)

	assert.Equal(t, http.StatusOK, w.Code)
	assert.Equal(t, "", w.Body.String())

 

以上是关于gin框架timeout超时的主要内容,如果未能解决你的问题,请参考以下文章

gin框架timeout超时

gin框架timeout超时

Gin 接口超时控制

xhr 设置超时 timeout

gin实践

连接FastDFS出现超时问题的解决办法