Home > Backend Development > Golang > How to Stop Go\'s JSON Marshaler from Converting \'&\' to \'&\'?

How to Stop Go\'s JSON Marshaler from Converting \'&\' to \'&\'?

DDD
Release: 2024-12-01 13:09:11
Original
997 people have browsed it

How to Stop Go's JSON Marshaler from Converting '&' to '&'?

How to Prevent JSON from Converting '&' to '&'?

Problem Scenario

Consider the following code snippet:

package main</p>
<p>import (</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">"encoding/json"
"fmt"
"log"
"net/http"
Copy after login

)

func testFunc(w http.ResponseWriter, r *http.Request) {

data := make(map[string]string)
data["key"] = "&"
bytes, err := json.Marshal(data)
if err != nil {
    fmt.Fprintln(w, "generator json error")
} else {
    //print console
    fmt.Println(string(bytes))
    fmt.Println("&")
    //print broswer
    fmt.Fprintln(w, string(bytes))
    fmt.Fprintln(w, "&")
}
Copy after login

}

func main() {

http.HandleFunc("/", testFunc)
err := http.ListenAndServe(":9090", nil)
if err != nil {
    log.Fatal("ListenAndServe", err)
}
Copy after login

}

Upon executing this code, we notice that the ampersand character ('&') is being converted to & in both the browser and console output, despite its intended display as '&'.

Solution

In Go 1.7, a new option was introduced to address this issue:

func (*Encoder) SetEscapeHTML
Copy after login

This function allows us to disable the escaping of HTML entities, including '&', '<', and '>'.

To implement this solution in the example code, we modify the testFunc function as follows:

func testFunc(w http.ResponseWriter, r *http.Request) {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">...

enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)

...
Copy after login

}

By disabling HTML escaping for the encoder, we ensure that the ampersand character is preserved as '&' in the JSON output, both in the browser and the console.

The above is the detailed content of How to Stop Go\'s JSON Marshaler from Converting \'&\' to \'&\'?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Previous article:Why Doesn\'t My Browser Store Cookies Set by My Go Server in a React App? Next article:How to Ensure Complete Data Transmission in a TCP Proxy?
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template