解决golang http.FileServer 遇到的坑

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

解决golang http.FileServer 遇到的坑

一名路过的小码农   2020-12-18 我要评论
这篇文章主要介绍了解决golang http.FileServer 遇到的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

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

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

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

http.ListenAndServe("8080", nil)

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

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

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

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

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

加一个StripPrefix 方法就好了

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

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

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

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

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

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

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

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

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

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)
  }
}

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们