How to manage double quote strings in Go

I need to send some text which already consists double quotes as string

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

as you can see this string is invalid

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

I know about this trick, but is there a more handy method to solve this issue, because I am receiving 200 lines of html, I should insert into it some values and return it back with some additional data.

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

Here I am calling GraphQL resolver and html variable is my html string with already inserted values, the issue is that this query covers my string with additional double quotes and even I use this method to remove them

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

after graphql query is looks like

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

Hi. Sorry i think I was replaying to your question a little bit too fast

  1. You should use Sprintf like this:
str := fmt.Sprintf(`{"query": "{sendMailToRec(theme: \"%s\", html: \"%s\", recipientList: \"%s\"){theme,html,recipientList} }"}`, theme, html, recipientList)

Iā€™m not quite sure what you mean by the two last rows. Is

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

The content of html and you need to escape all the quotes inside the GraphQL call. You must convert all of your quotes inside it so it looks like this

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

the easiest way is to convert all occurrances of " to \" like this

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

Do I make sense?

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.