spy16 / droplets

Droplets is a platform for Gophers.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ListenAndServe() needs to panic

sofasurfa opened this issue · comments

Hi, I'm new to GoLang. But looking at the code, I think that ListenAndServe() needs to fatal log that will call panic and stop the programme. If ListenAndServe() is broken from the get go, take ListenAndServeTLS(certFile, keyFile), if something goes wrong with certFile then the program should crash, not return an error that we would only know about when we send an incoming signal (to start graceful shutdown). What do you think?

func (gss *Server) ListenAndServe() error {
	go func() {
		gss.server.Addr = gss.Addr
		if err := gss.server.ListenAndServe(); err != http.ErrServerClosed {
			// gss.err = err ---> no need for this
                        log.Fatal(err)  //  logs the error and calls panic
		}
	}()
	return gss.waitForShutdown()
}

You are absolutely right about the issue. (In fact it has happened in one of the production applications I wrote where I fixed it as well). Another scenario this issue can happen for example is when another application is already listening on Addr.

But fatal/panic is probably not the right solution. Because when the server exits (successfully or due to a problem), the main package might need to do some cleanups (For example, it connected to database and did a defer db.Close()).. If you do a fatal here, deferred statements will not execute. On the other hand, if you do panic, it won't crash the app because the panic would be in a non-main goroutine.

I think the right way to do this would be to use the gss.err inside waitForShutdown in someway and signal an error.

Made a quick fix for this and pushed. This can probably be simplified a bit. But it's not very complicated either.

@spy16 What you've said made a lot of sense. Thanks for your explanation and for pushing the code.
And big thanks for making this useful repository :)
Wishing u all the best!