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.

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

报告相同问题?

悬赏问题

  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并