登录
首页 >  Golang >  Go问答

GoLang 中为什么使用 ioutil.ReadFile() 读取文件时,无需指定 HTML 中链接的文件?

来源:stackoverflow

时间:2024-02-07 16:54:23 177浏览 收藏

golang学习网今天将给大家带来《GoLang 中为什么使用 ioutil.ReadFile() 读取文件时,无需指定 HTML 中链接的文件?》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我有一个 golang 脚本,旨在根据浏览器中的输入查询动态构建网页,如下所示 http://localhost:8000/blog/post#,使用的是 post# 部分确定要解析到我创建的 html 模板中的 json 数据文件;例如,如果我输入 http://localhost:8000/blog/post1 那么它会从我的 post1.json 文件创建一个 index.html 文件。目前,我的脚本在运行时允许我在浏览器中加载单个页面,然后退出并在终端标准输出日志中显示错误:

2022/03/18 00:32:02 error: open jsofun.css.json: no such file or directory
exit status 1

这是我当前的脚本:

package main

import (
    "encoding/json"
    "html/template"
    "io/ioutil"
    "log"
    "net/http"
    "os"
)

func bloghandler(w http.responsewriter, r *http.request) {
    blogstr := r.url.path[len("/blog/"):]

    blogstr = blogstr + ".json"

    // read the file in locally
    json_file, err := ioutil.readfile(blogstr)
    if err != nil {
        log.fatal("error: ", err)
    }

    // define a data structure
    type blogpost struct {
        // in order to see these elements later, these fields must be exported
        // this means capitalized naming and the json field identified at the end
        title       string `json:"title"`
        timestamp   string `json:"timestamp"`
        main        string `json:"main"`
        contentinfo string `json:"content_info"`
    }

    // json data
    var obj blogpost

    err = json.unmarshal(json_file, &obj)
    if err != nil {
        log.fatal("error: ", err)
    }

    tmpl, err := template.parsefiles("./blogtemplate.html")

    htmlfile, err := os.create("index.html")
    if err != nil {
        log.fatal(err)
    }

    defer htmlfile.close()

    tmpl.execute(htmlfile, obj)

    http.servefile(w, r, "./index.html")
}

func main() {
    http.handlefunc("/blog/", bloghandler)
    log.fatal(http.listenandserve(":8080", nil))
}

我做了一些基本的调试,发现问题出在以下几行:

json_file, err := ioutil.readfile(blogstr)
    if err != nil {
        log.fatal("error: ", err)
    }

令我困惑的是为什么 ioutil.readfile 也尝试读取我的 html 中链接的文件?浏览器不应该处理该链接而不是我的处理程序吗?作为参考,这是我的 html,其中链接了文件 jsofun.css ;控制台输出中引用的错误显示我的脚本正在尝试在调用 ioutil.readfile 期间以 jsofun.css.json 的形式访问此文件:

<!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>dynamic json events</title>
    <link rel="stylesheet" href="./jsofun.css"></style>
</head>
<body>
    <section id="title">
        <h1 id="text-title">{{.title}}</h1>
        <time id="timestamp">
            {{.timestamp}}
        </time>
    </section>
    <nav role="navigation" id="site-nav">
        <ul id="sitemap">
        </ul>
    </nav>
    <main role="main" id="main">
        {{.main}}
    </main>
    <footer role="contentinfo" id="footer">
        <section id="content-info" role="contentinfo">
            {{.contentinfo}}
        </section>
        <form id="contact-form" role="form">
        <address>
            contact me by <a id="my-email" href="mailto:[email protected]" class="my-email">e-mail</a>
        </address>
        </form>
    </footer>
<script src="./jsofun.js">
</script>
</body>
</html>

我知道我已将 .json 附加到以下行中的查询字符串:blogstr = blogstr + ".json",但是,我不明白为什么这也会影响我的 html 中的链接。我是否遗漏了什么或者为什么它会读取我的 html 模板中的链接?我想要 ioutil.readfile 做的就是读取解析到我的模板中的 json 文件。

编辑:我想补充一点,当我最初将页面加载到浏览器中时,它会成功加载 json 中的文本内容,但没有任何样式。当我查看源代码时,链接也是正确的,这让我很困惑为什么样式表不适用,因为它位于可以访问的正确目录中。这是我在浏览器中选择查看源时的源:

<!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>dynamic json events</title>
    <link rel="stylesheet" href="./jsofun.css"></style>
</head>
<body>
    <section id="title">
        <h1 id="text-title">second post test</h1>
        <time id="timestamp">
            friday, march 18th, 12:21am
        </time>
    </section>
    <nav role="navigation" id="site-nav">
        <ul id="sitemap">
        </ul>
    </nav>
    <main role="main" id="main">
        this is my second post where i am able to use dynamic url routing
    </main>
    <footer role="contentinfo" id="footer">
        <section id="content-info" role="contentinfo">
            this post was used primarily to test and layout how the rest of my posts will appear.
        </section>
        <form id="contact-form" role="form">
        <address>
            contact me by <a id="my-email" href="mailto:[email protected]" class="my-email">e-mail</a>
        </address>
        </form>
    </footer>
<script src="./jsofun.js">
</script>
</body>
</html>

作为参考,这是我的 json 文件的示例:

{
    "title" : "Second Post Test",
    "timestamp": "Friday, March 18th, 12:21AM",
    "main": "This is my second post where I am able to use dynamic URL routing",
    "content_info": "This post was used primarily to test and layout how the rest of my posts will appear."
}

正确答案


您的 go 服务器设置为/blog/ 路径提供服务,它通过执行 bloghandler 来实现这一点。您的 go 服务器中没有任何其他内容被设置为提供 css、js 或图像文件等资源。

对于此类事情,您通常需要在单独的路径注册单独的 FileServer 处理程序。示例:

func main() {
    http.handlefunc("/blog/", bloghandler)
    // to serve a directory on disk (/path/to/assets/on/my/computer)
    // under an alternate url path (/assets/), use stripprefix to
    // modify the request url's path before the fileserver sees it:
    http.handle("/assets/", http.stripprefix("/assets/",
        http.fileserver(http.dir("/path/to/assets/on/my/computer"))))
    log.fatal(http.listenandserve(":8080", nil))
}

您需要修复的另一件事是 html 中这些资产字段的链接,它们应该是绝对的,而不是相对的。

...
<link rel="stylesheet" href="/assets/jsofun.css"></style>
...
<script src="/assets/jsofun.js">

当然,仅当资产位于 /path/to/assets/on/my/computer 目录中时,上述内容才有效,例如

/path/to/assets/on/my/computer
├── jsofun.css
└── jsofun.js

bloghandler 不必要地为每个请求创建一个新文件而不删除它,这有可能很快将您的磁盘填满到其最大容量。要提供模板,您不需要创建新文件,您可以直接在 http.resposewriter 中执行模板。还建议仅解析模板一次,尤其是在生产代码中,以避免不必要的资源浪费:

type BlogPost struct {
    Title       string `json:"title"`
    Timestamp   string `json:"timestamp"`
    Main        string `json:"main"`
    ContentInfo string `json:"content_info"`
}

var blogTemplate = template.Must(template.ParseFiles("./blogtemplate.html"))

func blogHandler(w http.ResponseWriter, r *http.Request) {
    blogstr := r.URL.Path[len("/blog/"):] + ".json"

    f, err := os.Open(blogstr)
    if err != nil {
        http.Error(w, err.Error(), http.StatusNotFound)
        return
    }
    defer f.Close()

    var post BlogPost
    if err := json.NewDecoder(f).Decode(&post); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    if err := blogTemplate.Execute(w, post); err != nil {
        log.Println(err)
    }
}

让我们看看当您请求 http://localhost:8000/blog/post# 时会发生什么。

浏览器请求页面;您的代码成功构建并返回一些 html - 这将包括:

浏览器接收并处理html;作为该过程的一部分,它请求上面的 css。现在原始请求位于文件夹 /blog/post# 中,因此 ./jsofun.css 变为 http://localhost:8000/blog/jsofun.css

当你的go应用程序收到这个请求时,bloghandler将会被调用(由于请求路径);它删除 /blog/ 然后添加 .json 以获得文件名 jsofun.css.json。然后,您尝试打开此文件并收到错误,因为它不存在。

有几种方法可以解决这个问题;更改模板以使用 可能是一个开始(但我不知道 jsofun.css 存储在哪里,并且您没有显示任何可以使用的代码该文件)。我认为还值得注意的是,您不必在磁盘上创建文件 index.html (除非有其他原因这样做)。

(有关其他问题和进一步步骤,请参阅 mkopriva 的答案 - 当该答案发布时,我已经输入了一半,并且感觉该演练可能仍然有用)。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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