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

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

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)

代码

  1. func Main(w http.ResponseWriter, r *http.Request) error {
  2. match := Get("id1")
  3. if match {
  4. time.Sleep(1 * time.Minute)
  5. fmt.Println("Time Passed")
  6. return MainTmpl.Execute(w, nil)
  7. } else {
  8. return LoginTmpl.Execute(w, nil)
  9. }
  10. return nil
  11. }

请注意,我只翻译了代码部分,其他内容不会被翻译。

英文:

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

  1. func Main(w http.ResponseWriter, r *http.Request) error {
  2. match := Get("id1")
  3. if match {
  4. return MainTmpl.Execute(w, nil)
  5. time.Sleep(1 * time.Minute)
  6. fmt.Println("Time Passed")
  7. } else {
  8. return LoginTmpl.Execute(w, nil)
  9. }
  10. return nil
  11. }

答案1

得分: 1

return语句之后的任何代码都是无法执行的,因为在执行这些语句之前,函数就已经返回了。如果你想在回应被写入后的1分钟内打印一些内容,你可以这样做:

  1. func Main(w http.ResponseWriter, r *http.Request) error {
  2. match := Get("id1")
  3. if match {
  4. go func() {
  5. time.Sleep(1 * time.Minute)
  6. fmt.Println("Time Passed")
  7. }()
  8. return MainTmpl.Execute(w, nil)
  9. } else {
  10. return LoginTmpl.Execute(w, nil)
  11. }
  12. return nil
  13. }

这将启动一个 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:

  1. func Main(w http.ResponseWriter, r *http.Request) error {
  2. match := Get("id1")
  3. if match {
  4. go func() {
  5. time.Sleep(1 * time.Minute)
  6. fmt.Println("Time Passed")
  7. }()
  8. return MainTmpl.Execute(w, nil)
  9. } else {
  10. return LoginTmpl.Execute(w, nil)
  11. }
  12. return nil
  13. }

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:

确定