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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line