dou70260
2017-10-16 20:29
浏览 380
已采纳

http.ListenAndServe之后的golang执行功能

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • donglengli0644 2017-10-17 04:46
    已采纳

    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
    }
    
    点赞 评论
  • doufu1939 2017-10-16 20:51

    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.

    点赞 评论

相关推荐 更多相似问题