darkmist icon

Safe Encoding of string in Golang

darkmist | PRO | 12/04/16 09:56:52 PM UTC | 0 ⭐ | 260 👁️ | Never ⏰ | []
Go |

660 B

|

None

|

0 👍

/

0 👎

package main
 
import (
    "bytes"
    "encoding/json"
    "fmt"
)
 
type Search struct {
    Query string `json:"query"`
}
 
func main() {
    data := &Search{Query: "http://google.com/?q=stackoverflow&ie=UTF-8"}
    responseJSON, _ := JSONMarshal(data, true)
    fmt.Println(string(responseJSON))
 
}
 
func JSONMarshal(v interface{}, safeEncoding bool) ([]byte, error) {
    b, err := json.Marshal(v)
 
    if safeEncoding {
        b = bytes.Replace(b, []byte("\\u003c"), []byte("<"), -1)
        b = bytes.Replace(b, []byte("\\u003e"), []byte(">"), -1)
        b = bytes.Replace(b, []byte("\\u0026"), []byte("&"), -1)
    }
    return b, err
}

Comments