2

I want to use the embed features in Golang but I can't link up the CSS style to the HTML. I tried to find more information to see what I do wrong, but I could not find any help.

main.go

package main

import (
    "embed"
    "html/template"
    "net/http"
    "github.com/gorilla/mux"
)

//go:embed static
var fs embed.FS

//go:embed static/css
var css embed.FS

func testHandler(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFS(fs, "static/index.html")
    t.Execute(w, "")

}

func main() {

    r := mux.NewRouter()

    r.HandleFunc("/", testHandler)
    fileServer := http.FileServer(http.FS(css))

    //normally what I use
    //fileServer := http.FileServer(http.Dir("static"))

    http.Handle("/", r)
    http.Handle("/css/", fileServer)
    http.ListenAndServe(":8083", nil)
}

index.html

<!DOCTYPE html>
<html >
<head>
  <meta charset="UTF-8">
  <title>Responsive Table</title>
      <link rel="stylesheet" href="/css/style.css">
</head>

<h1>Hi</h1>

style.css

body {background-color: coral;}

Structure is as follows...

├── go.mod
├── go.sum
├── main.go
├── static
│   ├── css
│   │   └── style.css
│   └── index.html
6
  • Have you tried http.Handle("/css/", http.StripPrefix("/css", fileServer))? Commented Feb 23, 2023 at 19:42
  • Or http.Handle("/css/", http.FileServer(http.FS(fs))): without the strip-prefix middleware but rooted in static by using the fs variable (that should be functionally identical to http.FileServer(http.Dir("static"))) Commented Feb 23, 2023 at 19:45
  • For some reason, both of them do not work. Maybe I do something wrong. Commented Feb 23, 2023 at 19:56
  • Sorry, embed.FS actually uses the full paths as rooted from the source, even if you specify a deeply nested subdirectory. In other words, to access style.css in var css embed.FS you need to provide the path /static/css/style.css (it doesn't matter that you've used //go:embed static/css). Commented Feb 23, 2023 at 20:21
  • The easiest way would be to do http.Handle("/static/css/", http.FileServer(http.FS(fs))) and update the href in the HTML file. But if you want to serve the css files from /css/ you could do the opposite of what StripPrefix is doing by implementing an AddPrefix middleware function. Commented Feb 23, 2023 at 20:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.