Search code examples
gotimesleep

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


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
}

Solution

  • 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.