Making a Web Application Robust

This lesson shows how to make an application robust by making it able to withstand a minor panic.

We'll cover the following

When a handler function in a web application panics our web server simply terminates. This is not good: a web server must be a robust application, able to withstand what perhaps is a temporary problem. A first idea could be to use defer/recover in every handler-function, but this would lead to much duplication of code. Applying the error-handling scheme with closures is a much more elegant solution. Here, we show this mechanism applied to the simple web-server made previously, but it can just as easily be applied in any web-server program.

To make the code more readable, we create a function type for a page handler-function:

type HandleFnc func(http.ResponseWriter,*http.Request)

Our errorHandler function applied here becomes the function logPanics:

func logPanics(function HandleFnc) HandleFnc {
  return func(writer http.ResponseWriter, request *http.Request) {
    defer func() {
      if x := recover(); x != nil {
        log.Printf("[%v] caught panic: %v", request.RemoteAddr, x)
      }
    }()
  function(writer, request)
 }
}

And we wrap our calls to the handler functions within logPanics:

http.HandleFunc("/test1", logPanics(SimpleServer))
http.HandleFunc("/test2", logPanics(FormServer))

The handler-functions should contain panic calls or a kind of check(error) function.

Example

The complete code is listed here:

Get hands-on with 1400+ tech skills courses.