I tried to apply a mechanism that allow the go web server to be automatically restarted when it's stopped.
The way I do it, by putting the server.ListenAndServe()
inside an infinite loop. Since the .ListenAndServe()
is blocking, I felt it's ok to do that. Here are the full code:
func main() {
// ...
isStarted := false
for true {
if isStarted {
fmt.Println("===================================== RESTARTING WEB SERVER")
}
log.Println(server.ListenAndServe())
isStarted = true
time.Sleep(1 * time.Second)
}
}
When I run the app, what happen is quite different than what I expected. The web server won't start.
Am I doing it wrong? or is there any better and correct way? Thank you in advance
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:03 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:04 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:05 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:06 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:07 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:08 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:09 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:10 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:11 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:12 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:13 http: Server closed
===================================== RESTARTING WEB SERVER
2019/03/13 10:01:14 http: Server closed