douya1855 2013-03-19 19:02
浏览 33
已采纳

不提供http静态目录

I don't understand why my static resources aren't being served. Here is the code:

func main() {
    http.HandleFunc("/", get_shows)
    http.HandleFunc("/get",  get_show_json)
    http.HandleFunc("/set", set_shows)
    http.Handle("/css/", http.FileServer(http.Dir("./css")))
    http.Handle("/js/", http.FileServer(http.Dir("./js")))
    http.ListenAndServe(":8080", nil)
}

When I run the program, navigating to http://myhost.fake/css/ or to http://myhost.fake/css/main.css (these exists in the filesystem), I get a 404 error. The same is true if I replace "./css" with the full path to the directory. Ditto for the js static directory. My other handlers work fine. I am on a linux. Thanks!

  • 写回答

2条回答 默认 最新

  • duan19913 2013-03-19 19:24
    关注

    Your handler path (/css/) is passed to the FileServer handler plus the file after the prefix. That means when you visit http://myhost.fake/css/test.css your FileServer is trying to find the file ./css/css/test.css.

    The http package provides the function StripPrefix to strip the /css/ prefix.

    This should do it:

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

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)