doulu6929 2018-09-21 21:08
浏览 168

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
  • 写回答

1条回答

  • doukezi4576 2018-09-21 21:55
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥50 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗