Friday, May 17, 2024
HomeGolangWhich Golang router to make use of for what instances?

Which Golang router to make use of for what instances?


Once you begin to construct net purposes with Go, one of many first questions you’ll in all probability ask is 

“which golang router ought to I take advantage of?”

It’s not a straightforward query to reply, both. Most likely greater than 100 totally different routers are accessible, all with totally different APIs, options, and behaviors. So for this weblog put up I’ve evaluated 30 common ones, and created a shortlist of the perfect choices together with a flowchart that you should use to assist information your alternative.

Earlier than we begin, a couple of notes on terminology:

  • By helps method-based routing I imply that the router makes it simple to dispatch a HTTP request to totally different handlers primarily based on the request methodology ("GET""POST", and so on).
  • By helps variables in URL paths I imply that the router makes it simple to declare routes like /motion pictures/{id} the place {id} is a dynamic worth within the URL path.
  • By helps regexp route patterns I imply that the router makes it simple to declare routes like /motion pictures/{[a-z-]+} the place [a-z-]+ is a required regexp match within the URL path.
  • By helps host-based routes I imply that the router makes it simple to dispatch a HTTP request to totally different handlers primarily based on the URL host (like www.instance.com) slightly than simply the URL path.
  • By helps customized routing guidelines I imply that the router makes it simple so as to add customized guidelines for routing requests (reminiscent of routing to totally different handlers primarily based on IP deal with, or the worth in an Authorization header).
  • By conflicting routes I imply whenever you register two (or extra) route patterns that probably match the identical request URL path. For instance, if you happen to register the routes /weblog/{slug} and /weblog/new then an HTTP request with the trail /weblog/new matches each these routes.

Word: From a software program engineering perspective, conflicting routes are a unhealthy factor. They could be a supply of bugs and confusion, and it’s best to usually attempt to keep away from them in your purposes.

Shortlisted Golang router packages

4 totally different routers make the shortlist. They’re http.ServeMuxjulienschmidt/httproutergo-chi/chi and gorilla/mux. All 4 are well-tested, well-documented, and actively maintained. They (largely) have secure APIs, and are appropriate with http.Handlerhttp.HandlerFunc, and the customary middleware sample.

Concerning velocity, all 4 routers are quick sufficient for (nearly) each utility, and I like to recommend selecting between them primarily based on the particular options you want slightly than efficiency. I’ve personally used all 4 in-production purposes at totally different occasions and have been pleased with them.

Golang http.ServeMux

I’ll begin by saying that if you should use http.ServeMux, you in all probability ought to.

As a part of the Go customary library, it’s very battle examined and effectively documented. Utilizing it implies that you don’t must import any third-party dependencies, and most different Go builders will even be acquainted the way it works. The Go 1 compatibility promise additionally implies that it’s best to be capable to depend on http.ServeMux working the identical manner within the long-term. All of these issues are massive positives by way of utility upkeep.

In contrast to most different routers, it additionally helps host-based routes, incoming request URLs are mechanically sanitized, and the way in which that it matches routes is wise too: longer route patterns all the time take priority over shorter ones. This has the great side-effect which you can register patterns in any order and it gained’t change how your utility behaves.

The 2 major limitations of http.ServeMux are that it doesn’t assist method-based routing or variables in URL paths. However the lack of assist for method-based routing isn’t all the time a superb motive to keep away from it — it’s fairly simple to work round with some code like this:

func major() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", index)

    err := http.ListenAndServe(":3000", mux)
    log.Deadly(err)
}

func index(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        http.NotFound(w, r)
        return
    }

    // Frequent code for all requests can go right here...

    swap r.Technique {
    case http.MethodGet:
        // Deal with the GET request...

    case http.MethodPost:
        // Deal with the POST request...

    case http.MethodOptions:
        w.Header().Set("Permit", "GET, POST, OPTIONS")
        w.WriteHeader(http.StatusNoContent)

    default:
        w.Header().Set("Permit", "GET, POST, OPTIONS")
        http.Error(w, "methodology not allowed", http.StatusMethodNotAllowed)
    }
}

In these few traces, you’ve successfully obtained method-based routing, together with customized 404 and 405 responses and assist for OPTIONS requests. That’s much more than you get with many third-party routers.

Over time, I’ve come to comprehend that http.ServeMux has numerous positives and it’s completely ample in lots of instances. Actually, the one time I’d advocate not utilizing it’s whenever you want assist for variables in URL paths or customized routing guidelines. In these instances, attempting to work with http.ServeMux can get a bit bushy, and I feel it’s usually higher to go for a third-party router.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments