css文件由net/http包中的http.FileServer以html/text的形式发送
下面是一个使用http.FileServer方法提供html文件的简单web服务器。css文件以文本/html的形式发送,浏览器会抱怨,并且不使用csscss文件由net/http包中的http.FileServer以html/text的形式发送,html,css,go,Html,Css,Go,下面是一个使用http.FileServer方法提供html文件的简单web服务器。css文件以文本/html的形式发送,浏览器会抱怨,并且不使用css package main import ( "net/http" ) func main() { mux := http.NewServeMux() setupRoutes(mux) srv := &http.Server{ Addr: "127.0.0.1:9090&qu
package main
import (
"net/http"
)
func main() {
mux := http.NewServeMux()
setupRoutes(mux)
srv := &http.Server{
Addr: "127.0.0.1:9090",
Handler: mux,
}
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
println(err.Error())
return
}
println("Server starting on port,", "127.0.0.1:9090")
}
func setupRoutes(router *http.ServeMux){
router.Handle("/", http.FileServer(http.Dir("../web")))
}
html文件如下所示:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="../web/global.css">
</head>
<body>
<p> Test line</p>
</body>
</html>
p {
color: red
}
go
src
main
main.go
web
index.html
global.css
运行服务器并输入http://localhost:9090/ 在浏览器中。浏览器中的开发人员控制台报告以下错误:
localhost/:1 Refused to apply style from 'http://localhost:9090/web/global.css' because its
MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking
is enabled.
项目目录结构如下所示:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="../web/global.css">
</head>
<body>
<p> Test line</p>
</body>
</html>
p {
color: red
}
go
src
main
main.go
web
index.html
global.css
环境为:macOS 10.15.7;go版本go1.15.3达尔文/amd64;
谷歌浏览器-86.0.4240.111版(官方版本)(x86_64)
你知道怎么解决这个问题吗
谢谢 如下更改项目目录结构
go
src
main.go
web
index.html
global.css
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="/global.css">
</head>
<body>
<p> Test line</p>
</body>
</html>
func setupRoutes(router *http.ServeMux) {
router.Handle("/", http.FileServer(http.Dir("./web")))
}
并更改html文件,如下所示
go
src
main.go
web
index.html
global.css
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="/global.css">
</head>
<body>
<p> Test line</p>
</body>
</html>
func setupRoutes(router *http.ServeMux) {
router.Handle("/", http.FileServer(http.Dir("./web")))
}
在浏览器的控制台中检查文件的内容,我猜它找不到文件,而响应实际上是404 html页面,或者类似的东西。如果是这种情况,您需要确保您的http.Dir是准确的,并且确实可以访问该文件,然后,您需要确保您的
href
准确无误,并实际将请求发送到http.FileServer提供服务的正确位置。您可以使用curl:curl来代替浏览器控制台进行检查http://localhost:9090/web/global.css
,您得到css还是404?请不要使用相对路径。这行不通。