why i can't connect css file using gorilla/mux.Router net/http.Handle

Issue

I looked at all similar questions and connected the file as it was said there, but despite this, the file does not work.
I don’t know what to do, what did I do wrong

main.go

func main() {
    r := mux.NewRouter()
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
    r.HandleFunc("/index", index)
    http.ListenAndServe(":8080", r)
}
func index(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./static/html/test.html")
}

structure

test.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" type="text/css" href="/static/css/test.css" />
    </head>
    <body class="sb-nav-fixed">
        asdfasd
    </body>
</html>

test.css

body{
    height: 100%;
    width: 100%;
    background-color: brown;
}

Solution

you can’t mix net/http.Handle and gorilla/mux.Router

you can do it like this

func main() {
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
    http.HandleFunc("/index", index)
    http.ListenAndServe(":8080", nil)
}
func index(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./static/html/test.html")
}

or like this

func main() {
    r := mux.NewRouter()
    r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
    r.HandleFunc("/index", index)
    http.ListenAndServe(":8080", r)
}
func index(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./static/html/test.html")
}

Answered By – delpid

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published