在模板执行后如何实现 time.Sleep?

huangapple go评论71阅读模式
英文:

How to implement the time.Sleep after the template execution?

问题

在这个函数中,我希望在主模板执行后等待一段时间再打印消息,但是出现了两个问题。

  1. 它需要1分钟来加载模板,而不是在模板执行后等待。
  2. 它给出了添加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.

  1. It takes 1 minute to load a template instead of sleeping after the template execution.
  2. It gives the message to add the return. When I write return nil, it gives me another error on this code time.Sleep(5 * time.Second) fmt.Println("Time Passed") that unreachable 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.

huangapple
  • 本文由 发表于 2021年10月2日 02:07:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/69410295.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定