繁体   English   中英

Golang 从 JSON 字符串数据中读取 html 标签 (<>) 作为 < 和 > 导致浏览器渲染问题

[英]Golang reads html tags (<>) from JSON string data as &lt and &gt which causes rendering issues in the browser

我有一个基本的 web 服务器,它从 JSON 帖子的数据库中呈现博客帖子,其中主要段落是从 JSON 字符串数组构建的。 我试图找到一种方法来轻松地对新行或换行符进行编码,但发现这些值的编码如何从 JSON 变为 GoLang 并最终变为我的 HTML 网页时遇到了很多困难。 当我尝试用换行符对我的 JSON 进行编码时,我发现我必须使用\\n而不是仅仅使用\n n 来对它们进行编码,以便它们实际出现在我的页面上。 然而,一个问题是它们只是作为文本出现,而不是换行符。

然后,我尝试研究将连接字符串数组的\n部分替换为<br>标记的方法,但是我找不到任何方法来使用 go 进行此操作,并转而尝试在 javascript 中进行此操作。这也没有用尽管我在 HTML 的链接中推迟了对 javascript 的调用。这是 javascript:

var title = window.document.getElementById("title");
var timestamp = window.document.getElementById("timestamp");
var sitemap = window.document.getElementById("sitemap");
var main = window.document.getElementById("main");
var contact_form = window.document.getElementById("contact-form");
var content_info = window.document.getElementById("content-info");

var str = main.innerHTML;

function replaceNewlines() {
    // Replace the \n with <br>
    str = str.replace(/(?:\r\n|\r|\n)/g, "<br>");

    // Update the value of paragraph
    main.innerHTML = str;
}

这是我的 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>Dynamic JSON Events</title>
    <link rel="stylesheet" href="/blogtemplate.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">
        {{.ParsedMain}}
    </main>
    <footer role="contentinfo" id="footer">
        <form id="contact-form" role="form">
        <address>
            Contact me by <a id="my-email" href="mailto:antonhibl11@gmail.com" class="my-email">e-mail</a>
        </address>
        </form>
    </footer>
<script defer src="/blogtemplate.js">
</script>
</body>
</html>

然后,我最终转而尝试将<br>标签硬编码到我的 json 数据中,发现当它最终到达浏览器时,它只是呈现为 &lt 和 &gt。 我对这种编码过程感到非常沮丧,不断导致我在创建换行符和换行符时出现问题。 如何在我的 JSON 字符串数据中轻松地包含我想要的换行符?

如果有帮助,这是我的 Go 脚本:

package main

import (
    "encoding/json"
    "html/template"
    "log"
    "net/http"
    "os"
    "regexp"
    "strings"
)

type BlogPost struct {
    Title      string   `json:"title"`
    Timestamp  string   `json:"timestamp"`
    Main       []string `json:"main"`
    ParsedMain string
}

// this did not seem to work when I tried to implement it below
var re = regexp.MustCompile(`\r\n|[\r\n\v\f\x{0085}\x{2028}\x{2029}]`)
func replaceRegexp(s string) string {
    return re.ReplaceAllString(s, "<br>\n")
}

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

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

    f, err := os.Open("db/" + 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
    }

    post.ParsedMain = strings.Join(post.Main, "")

    // post.ParsedMain = replaceRegexp(post.ParsedMain)

    if err := blogTemplate.Execute(w, post); err != nil {
        log.Println(err)
    }
}

func teapotHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusTeapot)
    w.Write([]byte("<html><h1><a href='https://datatracker.ietf.org/doc/html/rfc2324/'>HTCPTP</h1><img src='https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftaooftea.com%2Fwp-content%2Fuploads%2F2015%2F12%2Fyixing-dark-brown-small.jpg&f=1&nofb=1' alt='Im a teapot'><html>"))
}

func faviconHandler(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./assets/art/favicon.ico")
}

func main() {
    http.Handle("/", http.FileServer(http.Dir("/assets/docs")))
    http.HandleFunc("/blog/", blogHandler)
    http.HandleFunc("/favicon.ico", faviconHandler)
    http.HandleFunc("/teapot", teapotHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

这是我的 JSON 数据的示例:

{
    "title" : "Finished My First Blog App",
    "timestamp": "Friday, March 18th, 11:39 AM",
    "main": [
        "It took me awhile to tidy everything up but I finally finished creating my first ",
        "blog app using Go along with JSON for my database. I plan on using this to document ",
        "my own thoughts and experiences as a programmer and cybersecurity researcher; things ",
        "like tutorials, thought-pieces, and journals on my own projects progress will be ",
        "posted here. I look forward to getting more used to writing and sharing my own story, ",
        "I think it will help me learn from doing and also hearing feedback from others.\\n\\n",
        "I utilized a handler function to dynamically read from my JSON database and template ",
        "data into my HTML template using the go html/template package as well as the encoding/json ",
        "to handling reading those objects. Next I had to make sure my CSS and JavaScript assets ",
        "would be served alongside this finished template in order for my styling to be output into ",
        "the browser. For this I used a FileServer function which allowed for me to serve linked ",
        "resources in my HTML boilerplate and have the server still locate blog resources dynamically. ",
        "Going forward I am looking to add better styling, more JavaScript elements to the page, and ",
        "more functionality to how my JSON data is encoded and parsed in order to create more complex ",
        "looking pages and blog posts."
    ]
}

我只是想找到一种方法来轻松地在我的 JSON 中的长字符串数组中的段落之间包含空格但是我在 Go 中失败了,我的 JS 似乎从来没有影响我的网页(这不是我遇到的唯一问题有了这个,由于某种原因它似乎不想影响任何页面元素),而且我似乎无法将<br>标签直接硬编码到我的 JSON 中,因为浏览器将它们解释为&lt;br&gt;&lt;br&gt; . 我尝试过的任何事情实际上都没有让我对换行符进行编码,我可以在这里做什么?

您可以尝试在模板内遍历数组并为数组的每个元素生成 ap 标记。 这样就不需要编辑 go 中的主数组。

模板:

<!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="/blogtemplate.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">
        {{range $element := .Main}} <p>{{$element}}</p> {{end}}
    </main>
    <footer role="contentinfo" id="footer">
        <form id="contact-form" role="form">
        <address>
            Contact me by <a id="my-email" href="mailto:antonhibl11@gmail.com" class="my-email">e-mail</a>
        </address>
        </form>
    </footer>
<script defer src="/blogtemplate.js">
</script>
</body>
</html>

如果您希望 JSON 文档包含 HTML,则执行以下操作:

  1. 将 ParsedMain 更改为类型html.HTML

     type BlogPost struct {... ParsedMain html.HTML }
  2. 分配字段时转换为该类型:

     post.ParsedMain = html.HTML(strings.Join(post.Main, "")).
  3. 将 ``\n with
    ` 在文档中。

如果不受信任的用户可以输入 JSON 文档数据,那么应用程序应该根据允许列表过滤 HTML 标签和属性。 这可以防止攻击者通过脚本注入发起攻击。

如果要将 JSON 文档中的换行符转换为 HTML 中的换行符,请执行以下操作:

  1. 更改文档以包含换行符: \\n -> \n

  2. 在服务器或客户端上,将换行符替换为 HTML 换行符。 为防止脚本注入攻击,请在插入<br>之前转义 HTML。 以下是在服务器上执行此操作的方法:

     type BlogPost struct {... ParsedMain html.HTML } escapedAndJoined:= html.Escaper(post.Main...) post.ParsedMain = html.HTML(strings.ReplaceAll(escapedAndJoined, "\n", "<br>"))).

您可能想使用<p>而不是<br>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM