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

Static file handler

Whilst we are mostly going to be dealing with APIs in this book, it is a useful illustration to see how the default router and paths work by adding a secondary endpoint.

As a little exercise, try to modify the code in reading_writing_json_5/reading_writing_json_5.go to add an endpoint /cat, which returns the cat picture specified in the URI. To give you a little hint, you are going to need to use the FileServer function on the net/http package and your URI will look something like http://localhost:8080/cat/cat.jpg.

Did it work the first time or did you forget to add the StripPrefix handler?

Example 1.7 reading_writing_json_6/reading_writing_json_6.go:

21 cathandler := http.FileServer(http.Dir("./images")) 
22 http.Handle("/cat/", http.StripPrefix("/cat/", cathandler))

In the preceding example, we are registering a StripPrefix handler with our path /cat/. If we did not do this, then the FileServer handler would be looking for our image in the images/cat directory. It is also worth reminding ourselves about the difference with /cat and /cat/ as paths. If we registered our path as /cat then we would not match /cat/cat.jpg. If we register our path as /cat/, we will match both /cat and /cat/whatever.

主站蜘蛛池模板: 农安县| 信阳市| 安图县| 屏南县| 定陶县| 昆山市| 永泰县| 双江| 蚌埠市| 木兰县| 平塘县| 米脂县| 平塘县| 澎湖县| 临泉县| 马龙县| 高平市| 定安县| 迁安市| 成武县| 东海县| 内丘县| 安顺市| 永济市| 五河县| 霞浦县| 莱阳市| 罗定市| 宾阳县| 井冈山市| 莱阳市| 金华市| 五指山市| 岳阳县| 永靖县| 泉州市| 泰兴市| 东台市| 信丰县| 嘉祥县| 章丘市|