【问题标题】:How to include css to go lang app如何包含 css to go lang 应用程序
【发布时间】:2016-10-12 16:49:19
【问题描述】:

我在使用 go lang 创建的 Web 应用程序中添加一些 CSS 时遇到问题。 main.go 和 html 文件包含在根目录中,style.css 包含在 root/css 目录中

我的 .*go 代码是

package main

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

func main(){

    http.HandleFunc("/home", mainViewHandler)
    http.ListenAndServe(":8080", nil)
}

func mainViewHandler(responseWriter http.ResponseWriter,request *http.Request){

    t, _ := template.ParseFiles("main.html")
    t.Execute(responseWriter, 0)
}

而html代码是

<!DOCTYPE html>
<html lang="en">

    <head>
        <link rel="stylesheet" href="todo/style.css">
        <meta charset="UTF-8">
        <title>Main Page</title>

    </head>

    <body>
        <h2>Take your choice</h2>
        <a href="/edit">Edit</a>
        <a href="/add">Add</a>
        <a href="/list">List</a>
    </body>
</html>

【问题讨论】:

标签: css web-applications go


【解决方案1】:

你需要告诉 go 从 root/css 目录中提供文件。请记住,当您运行应用程序时,root/css 应该位于应用程序的工作文件夹中。

我不直接使用http包,但相信你的情况应该如下(在ListenAndServe之前):

http.Handle("/todo/", http.StripPrefix("root/css/", http.FileServer(http.Dir("root/css"))))

但您可能需要根据您的实际文件夹配置进行调整。

参见文档here

【讨论】:

  • 我之前尝试过这个解决方案,但它不起作用
  • 我必须添加一个“。”在我的道路之前 -_- ...感谢您的提示。
猜你喜欢
  • 1970-01-01
  • 2019-11-27
  • 1970-01-01
  • 2019-03-07
  • 2017-09-11
  • 2017-02-23
  • 2016-01-03
  • 2013-02-12
  • 1970-01-01
相关资源
最近更新 更多