Golang中如何管理双引号字符串

Golang中如何管理双引号字符串 我需要发送一些已经包含双引号的文本作为字符串

example := "<h1 style="exmaple">Hello</h1>"

如你所见,这个字符串是无效的

   example := "<h1 style=\"exmaple\">Hello</h1>"

我知道这个技巧,但是否有更方便的方法来解决这个问题,因为我收到了200行HTML,我需要在其中插入一些值,并添加一些额外数据后返回。

 str := fmt.Sprintf(`{"query": "{sendMailToRec(theme: \"` +  theme + `\", html: \"` +  html + `\", recipientList: \"` +  recipientList + `\"){theme,html,recipientList} }"}`)

这里我正在调用GraphQL解析器,html变量是我已经插入值的HTML字符串,问题是这个查询用额外的双引号包裹了我的字符串,即使我使用这种方法来移除它们

      example := "<h1 style=\"exmaple\">Hello</h1>"

在GraphQL查询之后,它看起来像

   "<h1 style="exmaple">Hello</h1>"

更多关于Golang中如何管理双引号字符串的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

你好。抱歉,我觉得我回复你的问题有点太快了。

  1. 你应该像这样使用 Sprintf:
str := fmt.Sprintf(`{"query": "{sendMailToRec(theme: \"%s\", html: \"%s\", recipientList: \"%s\"){theme,html,recipientList} }"}`, theme, html, recipientList)

我不太确定你最后两行是什么意思。是指:

example := "<h1 style=\"exmaple\">Hello</h1>"

这段 HTML 内容吗?并且你需要在 GraphQL 调用中转义所有的引号。你必须转换里面所有的引号,让它看起来像这样:

example := `<h1 style=\"exmaple\">Hello</h1>`

最简单的方法是将所有出现的 " 替换为 \",像这样:

example = strings.Replace(example, `"`, `\"`, -1)

我说得清楚吗?

更多关于Golang中如何管理双引号字符串的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中处理包含双引号的字符串时,使用原始字符串字面量(raw string literals)是最佳解决方案。原始字符串字面量使用反引号(`)而不是双引号,可以避免转义问题,特别适合处理HTML、JSON或GraphQL查询等复杂字符串。

对于你的具体情况,建议重构GraphQL查询的构建方式。不要通过字符串拼接来构造GraphQL查询,而是使用结构化的方法。以下是改进后的代码示例:

query := fmt.Sprintf(`{
    "query": "mutation { sendMailToRec(theme: %q, html: %q, recipientList: %q) { theme, html, recipientList } }"
}`, theme, html, recipientList)

这里使用了%q格式化动词,它会自动处理字符串中的引号转义。%q会将值格式化为带双引号的字符串,并自动转义其中的特殊字符。

如果你需要更精确地控制GraphQL查询格式,可以考虑使用Go的JSON序列化:

type GraphQLRequest struct {
    Query string `json:"query"`
}

graphQLQuery := fmt.Sprintf(`mutation { 
    sendMailToRec(theme: %q, html: %q, recipientList: %q) { 
        theme, html, recipientList 
    } 
}`, theme, html, recipientList)

request := GraphQLRequest{Query: graphQLQuery}
jsonData, err := json.Marshal(request)
if err != nil {
    // 处理错误
}
str := string(jsonData)

对于处理HTML字符串本身,使用原始字符串字面量:

html := `<h1 style="example">Hello</h1>
<div class="container">
    <p>This is a paragraph with "quotes" inside</p>
</div>`

如果你的HTML内容需要动态插入值,可以这样处理:

template := `<html>
<body>
    <h1>%s</h1>
    <div>%s</div>
</body>
</html>`

html := fmt.Sprintf(template, title, content)

这种方法避免了手动转义引号的麻烦,让代码更清晰且不易出错。

回到顶部