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

Time:06-12

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 >
        asdfasd
    </body>
</html>

test.css

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

CodePudding user response:

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")
}
  • Related