Serving CSS files

Hi,

I’ve been on a this for a while now and I’m done.

But my CSS files are not working, although I have ignored that part hoping to get help when I’m done with the Logic.

I have not seen and documentations on what to do to make my css files effective on my html page, however I’m guessing the project folder structure matters, and it will probably give clues to helping me solve the problem. The structure is below.

PATH |
- main.go
- database (database.go)
- templates ( index.html, styles( style1.css style2.css))

      - handlers
         handler.go

Thank you :relaxed:

It would be helpful if you told us what exactly is “not working” and what your code for the css looks like.

Further: use absolute paths. Your project structure should never matter.

Ok.

The problem is that I have a complete project and throughout the project, if I have to serve templates, I use this;

t, err := template.ParseFiles(“templates/index.html”) // templates reside in "templates"
if err != nil{
log.Println(“error”, err)
}
t.Execute(rw, nil)

I have used the tags properly in my html and css files and so when I execute a template, I expect to see a styled page with reagrds to my css. But I see just the html skeleton. Everything else works except that. (The pages are not rendered).

How do I fix this?

How do I use Absolute Path that Matt mentioned. Kindly recommend a doc or a code sample. I use Gorilla mux

I am assuming you have a webserver and are returning HTML through handlerFuncs instead of static files.
Inside your templates you then have something like

<link rel="stylesheet" href="some/Path/Maybe.css">

Looking at what error you get in your browser may hint you to where your problem is.
My first guess would be that you are not actually serving the .css files. You probably want to implement a Handler for the css files, something like this:

r.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))

Or if that suits you better even an individual handler for each file that reads the file and sends the contents back.

Also you should keep in mind when choosing your paths that wherever you start your server from will become your root.

1 Like

Ok, I’m still a little confused, however I’m getting clarity on this. Like you mentioned, I am not serving the css files, and how to do that, I don’t know. Can you explain the r.Handle a little more and the parameters.

I use Gorilla mux and these are my routes:

func serveWeb(){

myMux := mux.NewRouter()
myMux.HandleFunc("/", handlers.Home)
myMux.HandleFunc("/comment", handlers.Comment)
myMux.HandleFunc("/login", handlers.LoginPage)
myMux.HandleFunc("/signup", handlers.SignUp)
myMux.HandleFunc("/upage", handlers.ULPage)
myMux.HandleFunc("/say", handlers.PostComment)
myMux.Handle()
http.Handle("/", myMux)
err := http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux))
if err != nil{
    log.Fatal("ListenAndServe error: -> This error occured ", err)
}

}

func main() {
serveWeb()
}

How can I serve the CSS files here?

Thanks Jaytn :relaxed:

Hey @danny

Here’s a simple example that you can try to use to help yourself with.
I’m using a similar directory structure to what you’re using here to make it easier for you to understand.

It’s set up like so:


main.go
templates
- index.html (templates/index.html)
- styles (templates/styles)
-- index.css (templates/styles/index.css)


main.go

package main

import (
	"html/template"
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

var tmpls = template.Must(template.ParseFiles("templates/index.html"))

func Index(w http.ResponseWriter, r *http.Request) {
	data := struct {
		Title  string
		Header string
	}{
		Title:  "Index Page",
		Header: "Hello, World!",
	}

	if err := tmpls.ExecuteTemplate(w, "index.html", data); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", Index)

	r.PathPrefix("/styles/").Handler(http.StripPrefix("/styles/",
		http.FileServer(http.Dir("templates/styles/"))))

	http.Handle("/", r)
	log.Fatalln(http.ListenAndServe(":9000", nil))
}

index.html

<html>
	<head>
		<meta charset="UTF-8">
		<title>{{ .Title }}</title>
		<link rel="stylesheet" href="styles/index.css" />
	</head>
	<body>
		<h1>{{ .Header }}</h1>
	</body>
</html>

index.css

body {
	background: #1af;
}
2 Likes

I have had the same problem recently and also asked the question here : Serving static (css) files

In my case the problem was that I wasn’t running the main.go from the right directory path. Read the post maybe it will help :slight_smile:

You can check if Go an find your css files with this function below. I have left in my own comments to clarify.

// With this fucntion I can check if my filepath is working for serving static files such as CSS or Templates etc
// IMPORTANT:I failed to add static files because Go will use the current Directory you are in as the App's ROOT.
// If I run main.go from GolangBlog, the root is/Users/jorn/Documents/Golang/src/github.com/jschalkwijk/GolangBlog
// If I run it from jschalkwijk (my github folder)

 _, err := os.Stat(filepath.Join(".", "YourPathToCSSFolder/css", "style.css"))
checkErr(err)

This is working for me, also with Gorrila:
As I understand it, you are telling to strip /css/ if it is there, and then load the file from a specified folder.
r.PathPrefix("/css/").Handler(http.StripPrefix("/css/",http.FileServer(http.Dir("./YourWebAppFolder/static/css/"))))

HTML:
<link href="/css/style.css" type="text/css" rel="stylesheet"/>

Hope this helps, it got me really frustrated!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.