dtrgqjcd877528 2016-05-03 10:33
浏览 37

如何在httpRouter中使用timeouthandle

I am having some issues getting timeout to handle safely with github.com/julienschmidt/httprouter

I have tried setting the timeout when I initialize the http Server. This does timeout but I get no response back to the user at all.

HTTP := &http.Server{
    Addr:    ":" + port,
    Handler: muxWithMiddlewares,
    ReadTimeout:    1 * time.Second,
    WriteTimeout:   1 * time.Second,
    MaxHeaderBytes: 1 << 20,
}
HTTP.ListenAndServe()

I have also tried the technique suggested in the below stackoverflow link which explains how to get a timeout working with gorilla mux. This works the very first time a user calls the API, shows a timeout but subsequent requests still funciton as normal. Any help would be much appreciated.

How to use gorilla mux with http.TimeoutHandler

EDIT: Here is the code I tried first with the solution from the other stackoverflow article. As stated above it works for the first request and shows timeout but each request there after, the request can take however long it needs. Note I was mimicking a slow response by inputting time.Sleep(5*time.Second) inside the handlerA and handlerB here. I would think timeouthandler would run If any query takes longer than the time limit but that doesn't appear to be the way I have it configured at the moment in either of the solutions shown here.

router := httprouter.New()
router.GET("/xxx/", handlerA)
router.POST("/yyyy/", handlerB)
muxWithMiddlewares := http.TimeoutHandler(router, time.Second*1, "Timeout!")
err := http.ListenAndServe(":"+port, muxWithMiddlewares)
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
    • ¥15 谁有desed数据集呀
    • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
    • ¥15 关于#hadoop#的问题
    • ¥15 (标签-Python|关键词-socket)
    • ¥15 keil里为什么main.c定义的函数在it.c调用不了
    • ¥50 切换TabTip键盘的输入法