How to include CSS in HTML using Go?

huangapple go评论106阅读模式
英文:

How to include CSS in HTML using Go?

问题

我正在玩Go语言,但是似乎无法在Go中打开带有CSS的页面。当我在Go外部打开HTML文件时,CSS可以正常工作,但是当我通过Go运行时,CSS就没有被包含进去。

以下是你的代码:

  1. package main
  2. import (
  3. "fmt"
  4. "html/template"
  5. "log"
  6. "net/http"
  7. "strings"
  8. _ "github.com/go-sql-driver/mysql"
  9. )
  10. func sayhelloName(w http.ResponseWriter, r *http.Request) {
  11. r.ParseForm() //解析url传递的参数,对于POST则解析响应包的主体(request body)
  12. //注意:如果没有调用ParseForm方法,下面无法获取表单的数据
  13. fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息
  14. fmt.Println("path", r.URL.Path)
  15. fmt.Println("scheme", r.URL.Scheme)
  16. fmt.Println(r.Form["url_long"])
  17. for k, v := range r.Form {
  18. fmt.Println("key:", k)
  19. fmt.Println("val:", strings.Join(v, ""))
  20. }
  21. fmt.Fprintf(w, "Hello astaxie!") //这个写入到w的是输出到客户端的
  22. }
  23. func login(w http.ResponseWriter, r *http.Request) {
  24. fmt.Println("method:", r.Method) //获取请求的方法
  25. if r.Method == "GET" {
  26. t, _ := template.ParseFiles("Add-Vehicle.html")
  27. t.Execute(w, nil)
  28. } else {
  29. r.ParseForm()
  30. //逻辑处理的代码写在这里
  31. fmt.Println("username:", r.Form["select"])
  32. fmt.Println("password:", r.Form["select-1"])
  33. fmt.Println("username:", r.Form["year"])
  34. fmt.Println("password:", r.Form["text"])
  35. fmt.Println("username:", r.Form["dayrate"])
  36. }
  37. }
  38. func main() {
  39. http.HandleFunc("/", sayhelloName) //设置访问的路由
  40. http.HandleFunc("/login", login)
  41. http.Handle("/css/", http.FileServer(http.Dir("./css/")))
  42. err := http.ListenAndServe(":9090", nil) //设置监听的端口
  43. if err != nil {
  44. log.Fatal("ListenAndServe: ", err)
  45. }
  46. }

此外,这是我HTML文件中的href:

  1. <link rel="stylesheet" href="css/nicepage.css" media="screen">
  2. <link rel="stylesheet" href="css/Add-Vehicle.css" media="screen">

有人能帮我解决这个问题吗?

英文:

I am playing around with Go, but I can't seem to have the page open up with CSS, when I open the HTML file outside Go, the CSS works perfectly fine, but when I run it through Go, it's never included.

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;html/template&quot;
  5. &quot;log&quot;
  6. &quot;net/http&quot;
  7. &quot;strings&quot;
  8. _ &quot;github.com/go-sql-driver/mysql&quot;
  9. )
  10. func sayhelloName(w http.ResponseWriter, r *http.Request) {
  11. r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body)
  12. // attention: If you do not call ParseForm method, the following data can not be obtained form
  13. fmt.Println(r.Form) // print information on server side.
  14. fmt.Println(&quot;path&quot;, r.URL.Path)
  15. fmt.Println(&quot;scheme&quot;, r.URL.Scheme)
  16. fmt.Println(r.Form[&quot;url_long&quot;])
  17. for k, v := range r.Form {
  18. fmt.Println(&quot;key:&quot;, k)
  19. fmt.Println(&quot;val:&quot;, strings.Join(v, &quot;&quot;))
  20. }
  21. fmt.Fprintf(w, &quot;Hello astaxie!&quot;) // write data to response
  22. }
  23. func login(w http.ResponseWriter, r *http.Request) {
  24. fmt.Println(&quot;method:&quot;, r.Method) //get request method
  25. if r.Method == &quot;GET&quot; {
  26. t, _ := template.ParseFiles(&quot;Add-Vehicle.html&quot;)
  27. t.Execute(w, nil)
  28. } else {
  29. r.ParseForm()
  30. // logic part of log in
  31. fmt.Println(&quot;username:&quot;, r.Form[&quot;select&quot;])
  32. fmt.Println(&quot;password:&quot;, r.Form[&quot;select-1&quot;])
  33. fmt.Println(&quot;username:&quot;, r.Form[&quot;year&quot;])
  34. fmt.Println(&quot;password:&quot;, r.Form[&quot;text&quot;])
  35. fmt.Println(&quot;username:&quot;, r.Form[&quot;dayrate&quot;])
  36. }
  37. }
  38. func main() {
  39. http.HandleFunc(&quot;/&quot;, sayhelloName) // setting router rule
  40. http.HandleFunc(&quot;/login&quot;, login)
  41. http.Handle(&quot;/css/&quot;, http.FileServer(http.Dir(&quot;./css/&quot;)))
  42. err := http.ListenAndServe(&quot;:9090&quot;, nil) // setting listening port
  43. if err != nil {
  44. log.Fatal(&quot;ListenAndServe: &quot;, err)
  45. }
  46. }

Also here is the href on my html file

  1. &lt;link rel=&quot;stylesheet&quot; href=&quot;css/nicepage.css&quot; media=&quot;screen&quot;&gt;
  2. &lt;link rel=&quot;stylesheet&quot; href=&quot;css/Add-Vehicle.css&quot; media=&quot;screen&quot;&gt;

Would anyone be able to help me with this?

答案1

得分: 3

你正在为CSS链接使用相对路径,但你正在从/login而不是/处提供页面。因此,浏览器尝试从/login/css/而不是/css/获取文件。

你可以通过使用绝对路径来解决这个问题。

  1. <link rel="stylesheet" href="/css/nicepage.css" media="screen">
  2. <link rel="stylesheet" href="/css/Add-Vehicle.css" media="screen">

查看这个答案以了解更多关于相对路径和绝对路径行为的信息:https://stackoverflow.com/a/24028813/9208887。

此外,你应该从请求的URL中去掉/css前缀。

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

查看这个答案以了解为什么在这里使用StripPrefix很有用:https://stackoverflow.com/a/27946132/9208887。

英文:

You are using relative path for your CSS links, while you are serving the page from /login and not from /. So the browser is trying to get the files from /login/css/ instead of /css/.

You can fix that, by using an absolute path.

  1. &lt;link rel=&quot;stylesheet&quot; href=&quot;/css/nicepage.css&quot; media=&quot;screen&quot;&gt;
  2. &lt;link rel=&quot;stylesheet&quot; href=&quot;/css/Add-Vehicle.css&quot; media=&quot;screen&quot;&gt;

See this answer to learn more about relative and absolute path behaviour: https://stackoverflow.com/a/24028813/9208887.

Additionally, you should strip the /css prefix from the request's URL.

  1. fs := http.FileServer(http.Dir(&quot;./css&quot;))
  2. http.Handle(&quot;/css/&quot;, http.StripPrefix(&quot;/css&quot;, fs))

See this answer to learn why StripPrefix is useful here: https://stackoverflow.com/a/27946132/9208887.

答案2

得分: 0

http.FileServer还将请求文件的路径添加到本地文件搜索路径中。
因此,您的请求实际上是在“css”目录内请求一个文件“css/nicepage.css”。

在您的情况下,可以使用以下代码:

  1. http.Handle("/css/", http.FileServer(http.Dir("./")))

对于此类应用程序,使用根路径被认为是不好的做法,因此Web应用程序通常从专门分配给它们的目录中提供文件。通常称为“public”的目录将包含您的公共可访问文件,例如public/css、public/js等。

在这种情况下,您可以使用以下代码提供这些文件:

  1. http.Handle("/css/", http.FileServer(http.Dir("./public")))

这里有一个非常好的答案,可能会对您有所帮助:Golang. What to use? http.ServeFile(..) or http.FileServer(..)?

英文:

The http.FileServer also adds the path of the requested file to the local file search path.
So your request is actually requesting a file "css/nicepage.css" inside "css" directory - css/css/nicepage.css.

Something like this would work in your case:

  1. http.Handle(&quot;/css/&quot;, http.FileServer(http.Dir(&quot;./&quot;)))

Using root path would be considered bad for such application so web apps usually serve files from a directory specifically assigned for that. Usually this is called "public" and that directory would contain your publicly accessible files e.g. public/css, public/js, etc.

In this case you would serve them with:

  1. http.Handle(&quot;/css/&quot;, http.FileServer(http.Dir(&quot;./public&quot;)))

There's a very nicely written answer here, that might help you: Golang. What to use? http.ServeFile(..) or http.FileServer(..)?

huangapple
  • 本文由 发表于 2022年1月25日 03:21:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/70839351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定