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
Belin
  • 33
  • 4
  • Have you tried `http.Handle("/css/", http.StripPrefix("/css", fileServer))`? – mkopriva Feb 23 '23 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"))`) – mkopriva Feb 23 '23 at 19:45
  • For some reason, both of them do not work. Maybe I do something wrong. – Belin Feb 23 '23 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`). – mkopriva Feb 23 '23 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. – mkopriva Feb 23 '23 at 20:27
  • The following example works on my machine https://go.dev/play/p/TvLHzTCStdS. – mkopriva Feb 23 '23 at 20:29

0 Answers0