How to include CSS in HTML using Go?

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

How to include CSS in HTML using Go?

问题

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

以下是你的代码:

package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"strings"

	_ "github.com/go-sql-driver/mysql"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {
	r.ParseForm() //解析url传递的参数,对于POST则解析响应包的主体(request body)
	//注意:如果没有调用ParseForm方法,下面无法获取表单的数据
	fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息
	fmt.Println("path", r.URL.Path)
	fmt.Println("scheme", r.URL.Scheme)
	fmt.Println(r.Form["url_long"])
	for k, v := range r.Form {
		fmt.Println("key:", k)
		fmt.Println("val:", strings.Join(v, ""))
	}
	fmt.Fprintf(w, "Hello astaxie!") //这个写入到w的是输出到客户端的
}

func login(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method) //获取请求的方法
	if r.Method == "GET" {
		t, _ := template.ParseFiles("Add-Vehicle.html")
		t.Execute(w, nil)
	} else {
		r.ParseForm()
		//逻辑处理的代码写在这里
		fmt.Println("username:", r.Form["select"])
		fmt.Println("password:", r.Form["select-1"])
		fmt.Println("username:", r.Form["year"])
		fmt.Println("password:", r.Form["text"])
		fmt.Println("username:", r.Form["dayrate"])
	}
}

func main() {
	http.HandleFunc("/", sayhelloName) //设置访问的路由
	http.HandleFunc("/login", login)
	http.Handle("/css/", http.FileServer(http.Dir("./css/")))
	err := http.ListenAndServe(":9090", nil) //设置监听的端口
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}

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

<link rel="stylesheet" href="css/nicepage.css" media="screen">
<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.

package main
import (
&quot;fmt&quot;
&quot;html/template&quot;
&quot;log&quot;
&quot;net/http&quot;
&quot;strings&quot;
_ &quot;github.com/go-sql-driver/mysql&quot;
)
func sayhelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm() //Parse url parameters passed, then parse the response packet for the POST body (request body)
// attention: If you do not call ParseForm method, the following data can not be obtained form
fmt.Println(r.Form) // print information on server side.
fmt.Println(&quot;path&quot;, r.URL.Path)
fmt.Println(&quot;scheme&quot;, r.URL.Scheme)
fmt.Println(r.Form[&quot;url_long&quot;])
for k, v := range r.Form {
fmt.Println(&quot;key:&quot;, k)
fmt.Println(&quot;val:&quot;, strings.Join(v, &quot;&quot;))
}
fmt.Fprintf(w, &quot;Hello astaxie!&quot;) // write data to response
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println(&quot;method:&quot;, r.Method) //get request method
if r.Method == &quot;GET&quot; {
t, _ := template.ParseFiles(&quot;Add-Vehicle.html&quot;)
t.Execute(w, nil)
} else {
r.ParseForm()
// logic part of log in
fmt.Println(&quot;username:&quot;, r.Form[&quot;select&quot;])
fmt.Println(&quot;password:&quot;, r.Form[&quot;select-1&quot;])
fmt.Println(&quot;username:&quot;, r.Form[&quot;year&quot;])
fmt.Println(&quot;password:&quot;, r.Form[&quot;text&quot;])
fmt.Println(&quot;username:&quot;, r.Form[&quot;dayrate&quot;])
}
}
func main() {
http.HandleFunc(&quot;/&quot;, sayhelloName) // setting router rule
http.HandleFunc(&quot;/login&quot;, login)
http.Handle(&quot;/css/&quot;, http.FileServer(http.Dir(&quot;./css/&quot;)))
err := http.ListenAndServe(&quot;:9090&quot;, nil) // setting listening port
if err != nil {
log.Fatal(&quot;ListenAndServe: &quot;, err)
}
}

Also here is the href on my html file

    &lt;link rel=&quot;stylesheet&quot; href=&quot;css/nicepage.css&quot; media=&quot;screen&quot;&gt;
&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/获取文件。

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

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

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

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

fs := http.FileServer(http.Dir("./css"))
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.

&lt;link rel=&quot;stylesheet&quot; href=&quot;/css/nicepage.css&quot; media=&quot;screen&quot;&gt;
&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.

fs := http.FileServer(http.Dir(&quot;./css&quot;))
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”。

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

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

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

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

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:

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:

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:

确定