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
标签:httprouter,responses,ServeMux,Choosing,go,router,com,Greenlight From: https://www.cnblogs.com/zhangzhihui/p/18545686