英文:
How to implement the time.Sleep after the template execution?
问题
在这个函数中,我希望在主模板执行后等待一段时间再打印消息,但是出现了两个问题。
- 它需要1分钟来加载模板,而不是在模板执行后等待。
 - 它给出了添加
return的消息。当我写return nil时,它在这段代码time.Sleep(5 * time.Second) fmt.Println("Time Passed")上给出了另一个错误,即unreachable code。 
我在这个Main()函数中使用了中间件,以便不必为每个错误消息重复使用log.Fatal(err)。
代码
func Main(w http.ResponseWriter, r *http.Request) error {
    match := Get("id1")
    if match {
        time.Sleep(1 * time.Minute)
        fmt.Println("Time Passed")
        return MainTmpl.Execute(w, nil)
    } else {
        return LoginTmpl.Execute(w, nil)
    }
    return nil
}
请注意,我只翻译了代码部分,其他内容不会被翻译。
英文:
In this function, I want the time to sleep after the execution of the main template. and print the message after 1 minute is passed but it gives me two problems.
- It takes 1 minute to load a template instead of sleeping after the template execution.
 - It gives the message to add the 
return. When I writereturn nil, it gives me another error on this codetime.Sleep(5 * time.Second) fmt.Println("Time Passed")thatunreachable code. 
I used the middleware for this Main() function to not repeat log.Fatal(err) for each error message.
Code
func Main(w http.ResponseWriter, r *http.Request) error {
	match := Get("id1")
	if match {
		return MainTmpl.Execute(w, nil)
		time.Sleep(1 * time.Minute)
		fmt.Println("Time Passed")
	} else {
		return LoginTmpl.Execute(w, nil)
	}
    return nil
}
答案1
得分: 1
return语句之后的任何代码都是无法执行的,因为在执行这些语句之前,函数就已经返回了。如果你想在回应被写入后的1分钟内打印一些内容,你可以这样做:
func Main(w http.ResponseWriter, r *http.Request) error {
    match := Get("id1")
    if match {
        go func() {
           time.Sleep(1 * time.Minute)
           fmt.Println("Time Passed")
        }()
        return MainTmpl.Execute(w, nil)
    } else {
        return LoginTmpl.Execute(w, nil)
    }
    return nil
}
这将启动一个 goroutine,它会休眠一分钟然后打印内容。
英文:
Any code after a return statement is unreachable, because the function will return before executing those statements. If you want to print something 1 minute after the response is written, you can do:
func Main(w http.ResponseWriter, r *http.Request) error {
    match := Get("id1")
    if match {
        go func() {
           time.Sleep(1 * time.Minute)
           fmt.Println("Time Passed")
        }()
        return MainTmpl.Execute(w, nil)
    } else {
        return LoginTmpl.Execute(w, nil)
    }
    return nil
}
This will start a goroutine that will sleep for a minute and print.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论