ZhangZhihui's Blog  

We’re going to use the popular third-party package httprouter as the router for our application, instead of using http.ServeMux from the standard-library.

There are two reasons for this:

  • We want our API to consistently send JSON responses wherever possible. Unfortunately, http.ServeMux sends plaintext (non-JSON) 404 and 405 responses when a matching route cannot be found, and it’s not possible to easily customize these without causing a knock-on effect that inhibits the automatic sending of 405 responses. There is an open proposal to improve this in future versions of Go, but for now it’s a pretty significant drawback.
  • Additionally — and less importantly for most applications — http.ServeMux does not automatically handle OPTIONS requests.

Both of these things are supported by httprouter , along with providing all the other functionality that we need. The package itself is stable and well-tested, and as a bonus it’s also extremely fast thanks to its use of a radix tree for URL matching. If you’re building a REST API for public consumption, then httprouter is a solid choice.

 

zzh@ZZHPC:~/zd/Github/greenlight$ go get github.com/julienschmidt/httprouter@v1
go: downloading github.com/julienschmidt/httprouter v1.3.0
go: added github.com/julienschmidt/httprouter v1.3.0

 

Conflicting routes

It’s important to be aware that httprouter doesn’t allow conflicting routes which potentially match the same request. So, for example, you cannot register a route like GET /foo/new and another route with a parameter segment that conflicts with it — like GET /foo/:id .

If you’re using a standard REST structure for your API endpoints — like we will be in this book — then this restriction is unlikely to cause you many problems.

In fact, it’s arguably a positive thing. Because conflicting routes aren’t allowed, there are no routing-priority rules that you need to worry about, and it reduces the risk of bugs and unintended behavior in your application.

But if you do need to support conflicting routes (for example, you might need to replicate the endpoints of an existing API exactly for backwards-compatibility), then I would recommend taking a look at chi , Gorilla mux or flow instead. All of these are good routers which do permit conflicting routes.

 

Customizing httprouter behavior

The httprouter package provides a few configuration options that you can use to customize the behavior of your application further, including enabling trailing slash redirects and enabling automatic URL path cleaning.

More information about the available settings can be found here.

posted on 2024-11-14 11:51  ZhangZhihuiAAA  阅读(2)  评论(0编辑  收藏  举报