0

I'm trying to develop a simple web application but I'mhaving problem with serving my static files.

The file structure is:

  • main

--main.go

-serve

--listenAndServe.go

--templates

---login.html

---assets

----css

----fonts

----js

my code is this:

    import (
        "log"
        "net/http"
        "time"

        "github.com/gorilla/mux"
    )

    var (
        router = mux.NewRouter()
    )

    func (c *Conn) ListenAndServe() {
        fs := http.FileServer(http.Dir("./templates/assets"))
        http.Handle("/assets/", http.StripPrefix("/assets/", fs))
        router.HandleFunc("/", c.IndexPageHandler)
        router.HandleFunc("/login.html", c.LoginPageHandler)
        log.Println("Listening...")
        http.Handle("/", router)
        muxWithMiddlewares := http.TimeoutHandler(router, time.Minute*30, 
        "Timeout!")
         http.ListenAndServe(":8080", muxWithMiddlewares)
      }

But for some reason when I run it from main.go it serves the html but not the assets. I would really apreciate some tips. Thanks!

6
  • What (status) does the server respond with for your assets? Commented Aug 1, 2018 at 15:05
  • 5
    http.Handle("/assets/", http.StripPrefix("/assets/", fs)) and http.ListenAndServe(":8080", muxWithMiddlewares) are incompatible. The first one says "have the default ServeMux handle assets", the second says "start the server using the non-default muxWithMiddlewares handler". Use either the default mux, or the gorilla mux, but not both. Commented Aug 1, 2018 at 15:58
  • It doesn't actually responde with any errors. It just does not serve them. The HTML is served just fine Commented Aug 1, 2018 at 16:34
  • Thanks for clarify that @mkopriva! I'm trying to fix that Commented Aug 1, 2018 at 16:34
  • Try to remove the last slash for StripPrefix so that you have http.Handle("/assets/", http.StripPrefix("/assets", fs)) (or whatever you have after fixing the thing @mkopriva mentioned). I think i've had similar issues with FileServer not liking not having the leading slash Commented Aug 3, 2018 at 19:16

1 Answer 1

1

Try This:

mux.Handle("/static/", http.StripPrefix("/static", fileServer))

Note that static, in your case assets only has a single forward slash within the stripPreFix function.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.