(Newbie) Confusion on http fileserver default path

blov · 2017-07-26 09:00:08 · 549 次点击    
这是一个分享于 2017-07-26 09:00:08 的资源,其中的信息可能已经有所发展或是发生改变。

I am trying to figure out the following discrepancy in behavior for http.Handle

Consider this directory structure

myproject
    static
        index.html

And this code

fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)
http.ListenAndServe(":8080", nil)

running the above code and hitting http://localhost:8080/ or http://localhost:8080/index.html I will see the index.html served

however if I do something like this

fs := http.FileServer(http.Dir("./static"))
http.Handle("/test/", fs) // Comment: OR http.Handle("/test", fs)
http.ListenAndServe(":8080", nil)

running the above code and hitting http://localhost:8080/test or http://localhost:8080/test/index.html I will see 404 and no index.html

I feel this is a super rookie mistake, but I just can't wrap my head around it.

Can someone help me out?


评论:

ROFLLOLSTER:

Look at the second example here.

chmikes:

As the ROFLLOLSTER example shows, the FileServer will use the URL path to look into "./static". So it will look for "./static/test/index.html". You thus have to remove the segment of the path you don't want to be part in the file lookup.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

549 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传