-1

I'm building a web app and got to a point where I want to add css to my templates. I tried using embed + FileServer to serve my stylesheet but keep getting 404 whenever I tried to GET the file. What am I missing?

package main

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

//go:embed static
var css embed.FS

func main() {
    assets, _ := fs.Sub(css, "static")
    server := http.FileServer(http.FS(assets))
    router := mux.NewRouter()
    router.Handle("/static/", http.StripPrefix("/static", server))

    err := http.ListenAndServe(":8080", router)
    log.Fatal(err)
}

Crismar
  • 63
  • 1
  • 7
  • 1
    1. Never ignore errors. 2. Unless your CSS is under a path called "static/static", you probably don't want to be calling Sub(css, "static") on a filesystem that's already reading from "static" – Jonathan Hall Jun 23 '23 at 14:33

1 Answers1

0

Turns out the problem is how gorilla.mux matches addresses. See Golang Gorilla mux with http.FileServer returning 404

This is one way to correctly serve the files.

router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", server))
Crismar
  • 63
  • 1
  • 7