官术网_书友最值得收藏!

Paths

We already explained how ServeMux is responsible for routing inbound requests to the registered handlers, however the way that the routes are matched can be quite confusing. The ServeMux handler has a very simple routing model it does not support wildcards or regular expressions, with ServeMux you must be explicit about the registered paths.

You can register both fixed rooted paths, such as /images/cat.jpg, or rooted subtrees such as /images/. The trailing slash in the rooted subtree is important as any request that starts with /images/, for example /images/happy_cat.jpg, would be routed to the handler associated with /images/.

If we register a path /images/ to the handler foo, and the user makes a request to our service at /images (note no trailing slash), then ServerMux will forward the request to the /images/ handler, appending a trailing slash.

If we also register the path /images (note no trailing slash) to the handler bar and the user requests /images then this request will be directed to bar; however, /images/ or /images/cat.jpg will be directed to foo:

http.Handle("/images/", newFooHandler())
http.Handle("/images/persian/", newBarHandler())
http.Handle("/images", newBuzzHandler())
/images => Buzz
/images/ => Foo
/images/cat => Foo
/images/cat.jpg => Foo
/images/persian/cat.jpg => Bar

Longer paths will always take precedence over shorter ones so it is possible to have an explicit route that points to a different handler to a catch all route.

We can also specify the hostname, we could register a path such as search.google.com/ and /ServerMux would forward any requests to http://search.google.com and http://www.google.com to their respective handlers.

If you are used to a framework based application development approach such as using Ruby on Rails or ExpressJS you may find this router incredibly simple and it is, remember that we are not using a framework but the standard packages of Go, the intention is always to provide a basis that can be built upon. In very simple cases the ServeMux approach more than good enough and in fact I personally don't use anything else. Everyone's needs are different however and the beauty and simplicity of the standard packages makes it incredibly simple to build your own route as all is needed is an object which implements the Handler interface. A quick trawl through google will surface some very good third party routers but my recommendation for you is to learn the limitations of ServeMux first before deciding to choose a third-party package it will greatly help with your decision process as you will know the problem you are trying to solve.

主站蜘蛛池模板: 泰宁县| 信阳市| 马尔康县| 唐山市| 天峻县| 北票市| 江川县| 柳河县| 镇雄县| 东乡县| 中卫市| 多伦县| 蓝山县| 鄂温| 灯塔市| 巴中市| 海阳市| 措美县| 吴桥县| 富阳市| 民权县| 平阴县| 郧西县| 荥经县| 鹤山市| 甘洛县| 芒康县| 陇川县| 三穗县| 靖西县| 英德市| 宕昌县| 九龙城区| 镇原县| 岳普湖县| 通渭县| 黎川县| 正定县| 浦北县| 安溪县| 平罗县|