user2671513
user2671513

Reputation:

Go Serve static files , contents with router

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

Upvotes: 1

Views: 6792

Answers (1)

Simon Fox
Simon Fox

Reputation: 6425

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.

Upvotes: 5

Related Questions