Serving CSS files

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