Go 标准库 http.FileServer 实现静态文件服务
http.FileServer 方法属于标准库 net/http,返回一个使用 FileSystem 接口 root 提供文件访问服务的 HTTP 处理器。可以方便的实现静态文件服务器。 http.ListenAndServe(":8080", http.FileServer(http.Dir("/files/path"))) 访问 http://127.0.0.1:8080,即可看到类似 Nginx 中 autoindex 目录浏览功能。 源码解析 我们现在开始将上述的那仅有的一行代码进行剖析,看看到底是如何实现的。源码中英文注释也比较详细,可以参考。 我们先看 http.Dir(),再看 http.FileServer(),而 http.ListenAndServe() 监听 TCP 端口并提供路由服务,此处不赘述。 http.Dir() 从以下源码我们可以看出,type Dir string 实现了 type FileSystem interface 的接口函数 Open,http.Dir("/") 实际返回的是 http.Dir 类型,将字符串路径转换成文件系统。 // 所属文...

