gpt4 book ai didi

http - HTTP服务器HandleFunc循环超时?

转载 作者:行者123 更新时间:2023-12-01 22:27:53 25 4
gpt4 key购买 nike

我正在使用具有Web服务器的Go应用程序。我正在尝试添加超时并遇到问题。这是我制作的示例代码,因为不可能发布实际代码:

package main

import (
"fmt"
"html/template"
"net/http"
"time"
)

var layout *template.Template

func main() {
router := http.NewServeMux()
server := &http.Server{
Addr: ":8888",
Handler: router,
ReadTimeout: 5 * time.Second,
WriteTimeout: 1 * time.Second,
IdleTimeout: 15 * time.Second,
}

router.HandleFunc("/", home)

var err error
layout, err = template.ParseFiles("./layout.html")
if err != nil {
fmt.Printf("Error1: %+v\n", err)
}

server.ListenAndServe()
}

func home(w http.ResponseWriter, r *http.Request) {
fmt.Println("responding")
err := layout.Execute(w, template.HTML(`World`))
if err != nil {
fmt.Printf("Error2: %+v\n", err)
}
time.Sleep(5 * time.Second)
}

layout.html: Hello {{.}}!
当我运行它并访问127.0.0.1:8888时,浏览器保持加载状态,并且触发超时的 home()重新开始,并且在停止之前执行了10次,并且浏览器显示连接重置错误。

我期望超时后,函数将立即结束,连接将关闭,浏览器将停止加载并显示错误。

我该如何实现?

最佳答案

立即响应使用goroutine和上下文超时

package main

import (
"context"
"fmt"
"html/template"
"net/http"
"time"
)

var layout *template.Template
var WriteTimeout = 1 * time.Second

func main() {
router := http.NewServeMux()
server := &http.Server{
Addr: ":8889",
Handler: router,
ReadTimeout: 5 * time.Second,
WriteTimeout: WriteTimeout + 10*time.Millisecond, //10ms Redundant time
IdleTimeout: 15 * time.Second,
}
router.HandleFunc("/", home)
server.ListenAndServe()
}

func home(w http.ResponseWriter, r *http.Request) {
fmt.Printf("responding\n")
ctx, _ := context.WithTimeout(context.Background(), WriteTimeout)
worker, cancel := context.WithCancel(context.Background())
var buffer string
go func() {
// do something
time.Sleep(2 * time.Second)
buffer = "ready all response\n"
//do another
time.Sleep(2 * time.Second)
cancel()
fmt.Printf("worker finish\n")
}()
select {
case <-ctx.Done():
//add more friendly tips
w.WriteHeader(http.StatusInternalServerError)
return
case <-worker.Done():
w.Write([]byte(buffer))
fmt.Printf("writed\n")
return
}
}

关于http - HTTP服务器HandleFunc循环超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58736588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com