Skip to content

Instantly share code, notes, and snippets.

@obasekiosa
Created July 11, 2023 20:35
Show Gist options
  • Save obasekiosa/2fa81eb6692517fe6b3f98800c8e9123 to your computer and use it in GitHub Desktop.
Save obasekiosa/2fa81eb6692517fe6b3f98800c8e9123 to your computer and use it in GitHub Desktop.
Decode json to byte field (base64 encoded string) and re-encode gives a result different from the start json
package main
import (
"encoding/json"
"fmt"
"bytes"
)
type Obj struct {
Value []byte `json:"value"`
}
func main() {
data_arr := [][]byte {
[]byte("{\"value\":\"ose=\"}"),
[]byte("{\"value\":\"osa=\"}"),
[]byte("{\"value\":\"osc=\"}"),
[]byte("{\"value\":\"osY=\"}"),
}
for _, data := range data_arr {
runTests(data)
}
}
func runTests(data []byte) {
fmt.Println("Original: ", string(data))
fmt.Printf("After Decode and Encode: ")
tryDecode(data)
fmt.Println()
}
func tryDecode(data []byte) {
obj := Obj{}
r := bytes.NewReader(data)
err := json.NewDecoder(r).Decode(&obj)
if err != nil {
fmt.Printf("err1: ")
fmt.Println(err)
} else {
buf := new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(obj)
if err != nil {
fmt.Printf("err2: ")
fmt.Println(err)
} else {
fmt.Printf(buf.String())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment