代码之家  ›  专栏  ›  技术社区  ›  user1591668

golang为CSS文件提供正确的文件路径

go
  •  -2
  • user1591668  · 技术社区  · 6 年前

    我一直在阅读并尝试为我的HTML页面提供CSS文件,但没有任何效果。我一直在读这个 https://forum.golangbridge.org/t/serving-static-css-files/2051/10 以便更好地理解。我的项目结构如下

    func WebRoutes(r *mux.Router) {
        r.HandleFunc("/", Index)
    
       // Trying to serve file here and it's not working
        r.Handle("/web/content/desktop/", http.StripPrefix("/web/content/desktop/", http.FileServer(http.Dir("desktop"))))
    
       // Below is the correct path since it finds the file
        _, err := os.Stat(filepath.Join(".", "/web/content/desktop/", "page.css"))
         if err != nil {
            println(err.Error())
         }
    
    }
    

    我正在引用HTML页面中的文件,如下所示

     <link rel="stylesheet" type="text/css" href="/Web/Content/desktop/page.css">
    

    任何建议都是很好的,因为我似乎无法让我的CSS工作。

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   Adrian    6 年前

    您正在为静态文件提供以下服务:

    http.FileServer(http.Dir("desktop"))
    

    但是根据截图,磁盘上的路径不是 "desktop" 而是 "Web/Content/desktop" .

    记住,考虑到你已经在使用 StripPrefix ,除非您愿意,否则没有理由使用完整路径。你可以这样做:

    r.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("web/content/desktop"))))
    

    这会将URL更改为:

     <link rel="stylesheet" type="text/css" href="/css/page.css">