duanduo0520 2014-10-02 13:35
浏览 28
已采纳

用路由器去服务静态文件,内容

I am trying to serve static files which include javascript , css , html files

But it is failing to load all the external files in static directory

What did I do wrong?

Please help me

router := httprouter.New()

handler := func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  type Page struct {
    Title string
  }
  tp := template.Must(template.ParseFiles("templates/main.html", "templates/base.html"))
  tp.ExecuteTemplate(w, "base", &Page{Title: "AAAAA"})
}

router.Handle("GET", "/", handler)
// func (r *Router) Handle(method, path string, handle Handle)
// func (r *Router) Handler(method, path string, handler http.Handler)
// func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)

router.Handle("GET", "/aaa", aaa.aaaHandler)

router.Handle("POST", "/aaa_01_submit", aaa.aaa01Submit)
router.Handle("GET", "/aaa_01_run", aaa.aaa01Run)

http.Handle("/static", http.FileServer(http.Dir("static")))
http.ListenAndServe(":8000", router)

Here's my files

/app
    /templates
        main.html
        base.html
    /static
       /js
           files to read...
       /lib
       /css
main.go
  • 写回答

1条回答 默认 最新

  • dongyo7931 2014-10-02 13:48
    关注

    The problem is on these lines:

    http.Handle("/static", http.FileServer(http.Dir("static")))
    http.ListenAndServe(":8000", router)
    

    The first line registers the static file handler with the default mux. The second line runs the server with the root handler set to router. The default mux and the static file handler registered with it are ignored.

    There are a two ways to fix this:

    • Configure router to handle the static files using ServeFiles.

      router.ServeFiles("/static/*filepath", http.Dir("static"))
      
    • Register router with the default mux and use default mux as the root handler. Also, add a trailing "/" to "/static" to serve the entire tree and strip the "/static/" prefix for the file server.

      http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
      http.Handle("/", router)
      http.ListenAndServe(":8000", nil)
      

    These suggestions assume that you are serving the static resources using the URIs like "/static/js/example.js". If you are using URIs like "/js/example.js", then you need to register each of the directories in static individually.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源