【问题标题】:Нow to serve an HTML web page while rendering the CSS styling from an external stylesheet - styles being ignoredНow 在从外部样式表渲染 CSS 样式时提供 HTML 网页 - 样式被忽略
【发布时间】: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 的请求。

标签: html css go web server


【解决方案1】:

您需要确保为浏览器提供 css 文件,以便在呈现 HTML 页面时从您的服务器下载它。

在代码中,您需要有两个 http.Handle* 调用。坦率地说,我不知道如何在文件不在目录中的情况下执行此操作。

/html/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 v1.1 </title>
    <link rel="stylesheet" href="/css/style.css"> <!-- Emphasis here /css/style.css -->
</head>
<body>
    <h1>Simple Go Web Server v1.1</h1>
</body>
</html>

/static/css/style.css

(和你上面的代码一样)

/main.go

package main

import (
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", indexHandler)
    http.Handle("/css/", http.FileServer(http.Dir("static"))) // This is where we can tell go to serve the files in the static/css/ directory

    log.Fatal(http.ListenAndServe(":8081", nil))
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./html/index.html")
    return
}

【讨论】:

  • 谢谢。现在对我来说更有意义了。在 index.html 文件中,我链接到 css/style.css 样式表 - 但除非有一个 FileServer 实际托管/服务这个文件,否则它不能被使用。
猜你喜欢
  • 2014-01-19
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-22
  • 1970-01-01
相关资源
最近更新 更多