gpt4 book ai didi

解决golang http.FileServer 遇到的坑

转载 作者:qq735679552 更新时间:2022-09-27 22:32:09 27 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章解决golang http.FileServer 遇到的坑由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

上次写了一个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小例子 。

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
   "fmt"
   "net/http"
   "os"
   "path"
   "strings"
)
var staticfs = http.FileServer(http.Dir("D:\\code\\20160902\\src\\"))
func main() {
   //浏览器打开的时候显示的就是D:\\code\\20160902\\src\\client目录下的内容"
   http.Handle("/client/", http.FileServer(http.Dir("D:\\code\\20160902\\src\\")))
   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("访问静态文件:%s\n", 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("不能访问目录:%s\n", 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)
   }
}

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

原文链接:https://xiaochuan.blog.csdn.net/article/details/60326495 。

最后此篇关于解决golang http.FileServer 遇到的坑的文章就讲到这里了,如果你想了解更多关于解决golang http.FileServer 遇到的坑的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com