【发布时间】:2021-05-15 18:50:28
【问题描述】:
我正在尝试编写一个非常基本的 Web 服务器,它提供具有基本 css 样式的单个静态网页。
向“/”发出请求,然后显示 index.html 页面 - 带有样式。
问题:index.html 页面已显示,但样式未...“已应用” - 它似乎忽略了它。
我在这里看到了 3-5 个其他类似的问题,但都没有帮助。他们都建议使用从未解释过的“文件服务器”。我只想显示带有样式的html页面。我不明白为什么我们需要一个文件服务器来呈现带有一些样式的 HTML 页面。
我可以在 Python 中使用 flask 非常简单地通过“return render_template()”来实现这一点。
server.go:
package main
import (
"log"
"net/http"
)
func main() {
http.HandleFunc("/", indexHandler)
log.Fatal(http.ListenAndServe(":8081", nil))
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
return
}
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sam Wood | Simple Go Web Server</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Simple Go Web Server</h1>
</body>
</html>
* {
margin: 0;
padding: 0;
border: 0;
box-sizing: border-box;
}
body {
background-color: coral;
color: cadetblue;
}
【问题讨论】:
-
您正在使用 index.html 的内容回复每个请求。这包括对
style.css的请求。