登录
首页 >  Golang >  Go问答

在应用外部样式表的同时确保HTML页面正确显示CSS样式

来源:stackoverflow

时间:2024-02-23 23:54:25 127浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《在应用外部样式表的同时确保HTML页面正确显示CSS样式》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我正在尝试编写一个非常基本的 web 服务器,它提供具有基本 css 样式的单个静态网页。

因此,向“/”发出请求,然后显示 index.html 页面 - 带有样式。

问题:index.html 页面已显示,但样式未...“应用” - 它似乎只是忽略它。

我在这里看到了 3-5 个其他类似的问题,但没有一个有帮助。他们都建议使用“文件服务器”,但从未对此进行过解释。我只想显示 html 页面及其样式。我不明白为什么我们需要一个文件服务器来呈现带有某种样式的 html 页面。

我可以在python中使用flask非常简单地通过说“return render_template()”来实现这一点。

服务器.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:




    
    
    
    sam wood | simple go web server
    


    

simple go web server

* {
    margin: 0;
    padding: 0;
    border: 0;
    box-sizing: border-box;
}

body {
    background-color: coral;
    color: cadetblue;
}

解决方案


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

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

/html/index.html




    
    
    
    sam wood | simple go web server v1.1 
     


    

simple go web server v1.1

/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
}

终于介绍完啦!小伙伴们,这篇关于《在应用外部样式表的同时确保HTML页面正确显示CSS样式》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>