douwei8672 2018-01-14 09:57
浏览 156
已采纳

Golang net / http文件服务器以“ /”以外的任何模式提供404

Hello awesome stackoverflow community,

Apologies for the lame question. I've been playing around with the net/http package in Go, and was trying to set an http.Handle to serve the contents of a directory. My code to the Handle is

 func main() {
     http.Handle("/pwd", http.FileServer(http.Dir(".")))
     http.HandleFunc("/dog", dogpic)
     err := http.ListenAndServe(":8080", nil)
     if err != nil {
         panic(err)
     }
 } 

My dogpic handler is using os.Open and an http.ServeContent, which is working fine.

However, when I try to browse localhost:8080/pwd I am getting a 404 page not found, but when I change the pattern to route to /, as

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

it is showing the contents of the current page. Can someone please help me figure out why the fileserver is not working with other patterns but only /?

Thank you.

  • 写回答

2条回答 默认 最新

  • dptpn06684 2018-01-14 10:07
    关注

    The http.FileServer as called with your /pwd handler will take a request for /pwdmyfile and will use the URI path to build the filename. This means that it will look for pwdmyfile in the local directory.

    I suspect you only want pwd as a prefix on the URI, not in the filenames themselves.

    There's an example for how to do this in the http.FileServer doc:

    // To serve a directory on disk (/tmp) under an alternate URL
    // path (/tmpfiles/), use StripPrefix to modify the request
    // URL's path before the FileServer sees it:
    http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
    

    You'll want to do something similar:

    http.Handle("/pwd", http.StripPrefix("/pwd", http.FileServer(http.Dir("."))))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog