go / golang服务器中的静态CSS文件

How do I serve static css files in go (go version go1.9.1 linux/amd64)?

My present code doesn't work (it does show website but it does not see css). Here is my attempt to use standard file serving using go handler. When I go into page source and click link to css/styles.css it appears it is visible and redirects correctly (is under correct url). I presume I lack knowledge about some step of parsing.

package main

import (
    "html/template"
    "net/http"
    "fmt"
)

const (
    PORT = ":3000"
    HOST = "localhost"
)

func handleBooks(w http.ResponseWriter, r *http.Request) {
    tmpl := template.Must(template.ParseFiles("books.html"))
    tmpl.Execute(w)
}

func main() {
    fs := http.FileServer(http.Dir("css"))
    http.Handle("/css/", http.StripPrefix("/css/", fs))

    http.HandleFunc("/books", handleBooks)
    fmt.Println("Listening on " + HOST + PORT)
    http.ListenAndServe(PORT, nil)
}

style.css

.body {
    margin-left: auto;
    margin-right: auto;
    width: 1000px;
}

books.html

<html>
<head>
<title>Books</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<ul>
    books
        <li>book1</li>
        <li>book2</li>
</ul>
</body>
</html>

My directory tree:

  • src:
    • books.html
    • main.go
    • css
      • style.css

It seems that the problem was with this part:

fs := http.FileServer(http.Dir("css"))
http.Handle("/css/", http.StripPrefix("/css/", fs)) 

After I cleared cache it turned out that the slash in the first argument of http.Handle is necessary. Big thanks to mkopriva, without you I wouldn't have checked it.