Dylan
Dylan

Reputation: 305

Go http.Handle() not working as expected. 404 file not found

So I am trying to get CSS working using my Go server, but the css file is not loading correcly, I get 404 file not found. It works fine when I run Index.html straight from the browser.

My directory structure with # representing a folder and - a file:

- Main.go
# static
    - index.html
    # css
       - Styles.css

Index.html contains:

<link rel="stylesheet" type="text/css" href="css/Styles.css"/>

These are all my handlers:

muxRouter := mux.NewRouter()
muxRouter.HandleFunc("/", basicHandler)
muxRouter.HandleFunc("/ws", wsHandler)
muxRouter.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("static/css"))))

basicHandler contains:

toSend := template.HTMLEscapeString(outputMessage)
toSend = strings.Replace(toSend, "\n", "<br>", -1)

templateError := allTemplates.ExecuteTemplate(responseWriter, "index.html", template.HTML(toSend))
if templateError != nil {
    log.Fatal("Template error: ", templateError)
}

wsHandler handles the websocket which my program uses.

Upvotes: 0

Views: 855

Answers (1)

colm.anseo
colm.anseo

Reputation: 22037

I'd suggest moving your files like so (note I renamed index.html to lowercase - so it will be loaded by default when visiting the document root URL):

Main.go
static/
static/index.html
static/css/Styles.css

modify index.html to refer to the more aptly named css directory:

<link rel="stylesheet" type="text/css" href="css/Styles.css"/>

EDIT: update to adjust for gorilla/mux.

H/T to this answer.

package main

import (
        "github.com/gorilla/mux"
        "log"
        "net/http"
)

func main() {
        r := mux.NewRouter()

        r.PathPrefix("/css/").Handler(
                http.StripPrefix("/css/", http.FileServer(http.Dir("static/css/"))),
        )   

        err := http.ListenAndServe(":8080", r)
        if err != nil {
                log.Fatal(err)
        }   

        // curl 'localhost:8080/css/Styles.css'
        // <style> ...  </style>
}

Upvotes: 2

Related Questions