您的位置:首页技术文章

解决golang http.FileServer 遇到的坑

【字号: 日期:2023-11-29 19:51:15浏览:2作者:馨心

上次写了一个2行实现一个静态服务器的文章

今天群里有个哥们是这么写居然返回的是404 见鬼了嘛??

http.handle('/js', http.FileServer(http.Dir('js'))

http.ListenAndServe('8080', nil)

大概的意思就是绑定 路由为 js 的时候访问这个js 文件夹 看了一下确实代码上面没什么毛病。但是路径怎么修改 也不好使。

我把代码拿到我的 电脑上面运行 shitfuck 这是搞什么啊居然出现下面的这个情况

解决golang http.FileServer 遇到的坑

奇怪居然在我电脑上面也不能执行了。莫非我的文件夹权限有问题

给赋值一下 777 权限 重新运行

居然还不好使。来回改路径 就这么捣鼓了两个小时无意中看到一个文章就是说的这个

加一个StripPrefix 方法就好了

那这个玩意是干嘛的呢。看看手册

解决golang http.FileServer 遇到的坑

然后我的代码就变成这个样子

http.Handle('/js/', http.StripPrefix('/js/', http.FileServer(http.Dir('js'))))

http.StripPrefix用于过滤request,参数里的handler的request过滤掉特定的前序,只有这样,才能正确显示文件目录。 shitfuck

看一下我的路径 以及下面存放的文件

解决golang http.FileServer 遇到的坑

修改代码完成后就这么神奇般的解决了

解决golang http.FileServer 遇到的坑

浪费了两个小时不过 还不错最起码解决问题了。

补充:Golang1.8标准库http.Fileserver跟http.ServerFile小例子

我就废话不多说了,大家还是直接看代码吧~

package mainimport ( 'fmt' 'net/http' 'os' 'path' 'strings')var staticfs = http.FileServer(http.Dir('D:code20160902src'))func main() { //浏览器打开的时候显示的就是D:code20160902srcclient目录下的内容' http.Handle('/client/', http.FileServer(http.Dir('D:code20160902src'))) http.HandleFunc('/static/', static) http.HandleFunc('/js/', js) http.HandleFunc('/', route) http.ListenAndServe(':1789', nil)}func route(w http.ResponseWriter, r *http.Request) { fmt.Println(r.URL) fmt.Fprintln(w, 'welcome') r.Body.Close()}//这里可以自行定义安全策略func static(w http.ResponseWriter, r *http.Request) { fmt.Printf('访问静态文件:%sn', r.URL.Path) old := r.URL.Path r.URL.Path = strings.Replace(old, '/static', '/client', 1) staticfs.ServeHTTP(w, r)}//设置单文件访问,不能访问目录func js(w http.ResponseWriter, r *http.Request) { fmt.Printf('不能访问目录:%sn', r.URL.Path) old := r.URL.Path name := path.Clean('D:/code/20160902/src' + strings.Replace(old, '/js', '/client', 1)) info, err := os.Lstat(name) if err == nil { if !info.IsDir() { http.ServeFile(w, r, name) } else { http.NotFound(w, r) } } else { http.NotFound(w, r) }}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持优爱好网。如有错误或未考虑完全的地方,望不吝赐教。

标签: Golang
相关文章: