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

How it works…

Once we run the program, the HTTP server will start locally listening on port 8080. Browsing http://localhost:8080 will show us the same output we saw in our previous recipe, but this time the text color has changed from the default black to blue, as shown in the following image:

If we look at the Network tab of Chrome DevTools, we can see main.css, which has been loaded from the static/css directory present on the filesystem.

Let's understand the changes we introduced in the main() method as part of this recipe:

  • fileServer := http.FileServer(http.Dir("static")): Here, we created a file server using the FileServer handler of the net/http package, which serves HTTP requests from the static directory present on the filesystem.
  • http.Handle("/static/", http.StripPrefix("/static/", fileServer)): Here, we are registering the http.StripPrefix("/static/", fileServer) handler with the /static URL pattern using HandleFunc of the net/http package, which means  http.StripPrefix("/static/", fileServer) gets executed and passes (http.ResponseWriter, *http.Request) as a parameter to it whenever we access the HTTP URL with the /static pattern.
  • http.StripPrefix("/static/", fileServer): This returns a handler that serves HTTP requests by removing /static from the request URL's path and invokes the file server. StripPrefix handles a request for a path that doesn't begin with a prefix by replying with an HTTP 404.
主站蜘蛛池模板: 福州市| 宁蒗| 朝阳市| 双峰县| 苏州市| 晋江市| 肃宁县| 衡阳市| 额尔古纳市| 阜新市| 高台县| 安阳县| 化德县| 新安县| 斗六市| 盘锦市| 岳阳县| 苗栗市| 游戏| 阿合奇县| 全州县| 玉屏| 邳州市| 内江市| 定边县| 家居| 抚顺县| 铜山县| 吴桥县| 江华| 沐川县| 临邑县| 常宁市| 盐城市| 农安县| 嘉荫县| 松原市| 东光县| 灵武市| 金川县| 新乡市|