Constantin Druccdruc

Hey, I'm Constantin Druc!

I'm a web developer sharing everything I know about building web applications.

panic() in golang

Panic kills your server. Here's how to ensure that never happens.

Wrap handlers within a recoverPanic middleware

func (app *app) recoverPanic(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				// close connection after the response has been sent.
				w.Header().Set("Connection", "close")
				// 500 Internal Serve Error response.
				app.respondServerError(w, r, fmt.Errorf("%s", err))
			}
		}()

		next.ServeHTTP(w, r)
	})
}

use a goroutine helper

one that recovers and logs panics instead of letting them kill your server.

func (app *app) background(fn func()) {
    // use a wait group to wait for all goroutines to finish
    // before shutting down
	app.wg.Add(1)

	go func() {
		defer app.wg.Done()

		defer func() {
			if err := recover(); err != nil {
				app.logger.PrintError(fmt.Errorf("%s", err), nil)
			}
		}()

		fn()
	}()
}
Tags: