DEV Community

Cover image for Must Go: Cleaner Error Handling for Go HTTP Servers
devalanx
devalanx

Posted on

Must Go: Cleaner Error Handling for Go HTTP Servers

Hey folks đź‘‹

I’ve been working on a little package for Go that I think makes error handling in HTTP handlers a lot less painful. It’s called must_go, and it brings the Go “must” pattern to HTTP servers.

The Problem

If you’ve written any Go HTTP servers, you know the drill:

if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}
Enter fullscreen mode Exit fullscreen mode

You end up repeating this pattern everywhere. It clutters up your code and makes handlers harder to read.

The “Must” Pattern in Go

Go often uses the “must” pattern for functions where errors are unexpected or should crash fast. For example, template.Must or regexp.MustCompile. Instead of forcing you to handle errors at every call site, the “must” approach panics and lets the program crash (or recover in a controlled way).

must_go extends this idea to HTTP servers. You can write your handlers using must-style error handling, and middleware will recover and return proper HTTP responses instead of killing your app.

Features

  • Must(err): Panic if there’s an error.
  • MustWithMessage(err, msg): Add context.
  • MustHTTP(err, status, msg): Panic with HTTP status + message.
  • MustHTTPWithDefault(err): Automatically maps errors like “not found”, “unauthorized”, etc., to the right status codes.
  • Helpers like MustNotFound, MustBadRequest, MustInternal, and more.
  • Recovery middleware that catches panics and returns clean JSON:
{
  "error": {
    "message": "User not found",
    "status": 404
  }
}
Enter fullscreen mode Exit fullscreen mode

Quick Example

mux := http.NewServeMux()
mux.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
    err := fmt.Errorf("user not found")
    must_go.MustHTTP(err, http.StatusNotFound, "User not found")
})

handler := must_go.RecoveryMiddleware(mux)
http.ListenAndServe(":8080", handler)
Enter fullscreen mode Exit fullscreen mode

No boilerplate, no repeated if err != nil — just straight to the point.

Why Use It?

  • Implements the familiar Go “must” pattern for HTTP servers
  • Cleaner, more readable handlers
  • Automatic, consistent error responses
  • Keeps your business logic front and center

Try It Out

go get github.com/Devalanx/must_go
Enter fullscreen mode Exit fullscreen mode

Repo: github.com/Devalanx/must_go

I’d love feedback! 🚀
Give it a spin, open an issue, or suggest improvements.

Top comments (0)