golang execute function after http.ListenAndServe
Asked Answered
K

2

8

I am beginning to learn golang by creating a simple http server

func main() {
    f, err := os.OpenFile("testlogfile", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
    if err != nil {
        fmt.Println("error opening file: %v", err)
    }
    defer f.Close()

    log.SetOutput(f)

    http.HandleFunc("/", defaultHandler)
    http.HandleFunc("/check", checkHandler)

    serverErr := http.ListenAndServe("127.0.0.1:8080", nil) // set listen port

    if serverErr != nil {
        log.Println("Error starting server")

    } else {
        fmt.Println("Started server on - 127.0.0.1:8080" )
    }
}

The above code will start a local server on 8080 and I am able to hit the routes via browser. It's all good!

However, now I want to run a separate go routine, that watches a file -

func initWatch() string{
    watcher, err := fsnotify.NewWatcher()
    if err != nil {
        fmt.Println(err)
    }
    defer watcher.Close()

    done := make(chan bool)
    go func() {
        for {
            select {
                case event := <-watcher.Events:
                    if ( event.Op&fsnotify.Remove == fsnotify.Remove || event.Op&fsnotify.Rename == fsnotify.Rename ) {
                        fmt.Println("file removed - ", event.Name)
                    }

                case err := <-watcher.Errors:
                    fmt.Println("error:", err)
                }
        }
    }()

    err = watcher.Add("sampledata.txt")
    if err != nil {
        fmt.Println(err)
    }


    <-done
}

And now, if I call the function initWatch() BEFORE http.ListenAndServe("127.0.0.1:8080", nil) then I am not able to access the server routes via browser(ex - localhost:8080) because the sever has not spawned. Ex -

initWatch()
serverErr := http.ListenAndServe("127.0.0.1:8080", nil) // set listen port

And if I call the function initWatch() AFTER http.ListenAndServe("127.0.0.1:8080", nil) then the file watcher function is not working. Ex -

serverErr := http.ListenAndServe("127.0.0.1:8080", nil) // set listen port
initWatch()

How do I make both the initWatch()(file watcher) and the http server run?

Appreciate your help.

Karnes answered 16/10, 2017 at 20:29 Comment(1)
Perhaps explain what exactly initWatch() wants to do with routes? There's no code there to access localhost:8080. You can set up the router separately from the server, see docs for ListenAndServe. What error/problem do you see if putting before?Osana
A
6

You may start watcher in separate goroutine. After the server ends - you send signal to exit to the watcher. like:

done := initWatch()
serverErr := http.ListenAndServe("127.0.0.1:8080", nil)
done <- true

Next slightly modify watcher - return channel where to notify to stop working. Also working goroutine listens for exit signal.

func initWatch() chan bool {
    watcher, err := fsnotify.NewWatcher()
    if err != nil {
        fmt.Println(err)
    }
    defer watcher.Close()

    done := make(chan bool)
    go func() {
        for {
            select {
                case event := <-watcher.Events:
                    if ( event.Op&fsnotify.Remove == fsnotify.Remove || event.Op&fsnotify.Rename == fsnotify.Rename ) {
                        fmt.Println("file removed - ", event.Name)
                    }

                case err := <-watcher.Errors:
                    fmt.Println("error:", err)

                // listen exit signal
                case <- done:
                     break
            }
        }
    }()




    err = watcher.Add("sampledata.txt")
    if err != nil {
        fmt.Println(err)
    }
    return done
}
Anathematize answered 17/10, 2017 at 4:46 Comment(0)
M
3

Both calls, initWatch() and http.ListenAndServe("127.0.0.1:8080", nil) keep the main goroutine waiting forever. initWatch() is waiting for a value in the <-done statement, and never gets one. You should run initWatch or http.ListenAndServe in another goroutine, like go initWatch() for example. Or maybe send a value to the done channel from another goroutine.

Metaphosphate answered 16/10, 2017 at 20:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.