I need to encode the following string through base64 in golang
"{ \t\"signature\" = \"ZwXG56AezlHRTBhL8cTqA==\"; \t\"purchase-info\" = \"RXRjL0dNVCI7Cn0=\"; \t\"environment\" = \"Sandbox\"; \t\"pod\" = \"100\"; \t\"signing-status\" = \"0\"; }"
I try to do it as below
rec = []byte("{
\t\"signature\" = \"ZwXG56AezlHRTBhL8cTqA==\";
\t\"purchase-info\" = \"RXRjL0dNVCI7Cn0=\";
\t\"environment\" = \"Sandbox\";
\t\"pod\" = \"100\";
\t\"signing-status\" = \"0\";
}")
str := base64.StdEncoding.EncodeToString(rec)
fmt.Println(str)
Output
ewoJInNpZ25hdHVyZSIgPSAiWndYRzU2QWV6bEhSVEJoTDhjVHFBPT0iOwoJInB1cmNoYXNlLWluZm8iID0gIlJYUmpMMGROVkNJN0NuMD0iOwoJImVudmlyb25tZW50IiA9ICJTYW5kYm94IjsKCSJwb2QiID0gIjEwMCI7Cgkic2lnbmluZy1zdGF0dXMiID0gIjAiOwp9
However, it failed. Because the result is different with the base64 result through https://www.base64encode.org/, which is
e1xuXHRcInNpZ25hdHVyZVwiID0gXCJad1hHNTZBZXpsSFJUQmhMOGNUcUE9PVwiO1xuXHRcInB1cmNoYXNlLWluZm9cIiA9IFwiUlhSakwwZE5WQ0k3Q24wPVwiO1xuXHRcImVudmlyb25tZW50XCIgPSBcIlNhbmRib3hcIjtcblx0XCJwb2RcIiA9IFwiMTAwXCI7XG5cdFwic2lnbmluZy1zdGF0dXNcIiA9IFwiMFwiO1xufQ==
Then I try it in this way
data1 := []byte(`{
\t\"signature\" = \"ZwXG56AezlHRTBhL8cTqA==\";
\t\"purchase-info\" = \"RXRjL0dNVCI7Cn0=\";
\t\"environment\" = \"Sandbox\";
\t\"pod\" = \"100\";
\t\"signing-status\" = \"0\";
}`)
str1 := base64.StdEncoding.EncodeToString(data1)
fmt.Println(str1)
Output:
e1xuXHRcInNpZ25hdHVyZVwiID0gXCJad1hHNTZBZXpsSFJUQmhMOGNUcUE9PVwiO1xuXHRcInB1cmNoYXNlLWluZm9cIiA9IFwiUlhSakwwZE5WQ0k3Q24wPVwiO1xuXHRcImVudmlyb25tZW50XCIgPSBcIlNhbmRib3hcIjtcblx0XCJwb2RcIiA9IFwiMTAwXCI7XG5cdFwic2lnbmluZy1zdGF0dXNcIiA9IFwiMFwiO1xufQ==
Now the result is correct.
How to convert the original string from
[]byte("{
\t\"signature\" = \"ZwXG56AezlHRTBhL8cTqA==\";
\t\"purchase-info\" = \"RXRjL0dNVCI7Cn0=\";
\t\"environment\" = \"Sandbox\";
\t\"pod\" = \"100\";
\t\"signing-status\" = \"0\";
}")
to
[]byte(`{
\t\"signature\" = \"ZwXG56AezlHRTBhL8cTqA==\";
\t\"purchase-info\" = \"RXRjL0dNVCI7Cn0=\";
\t\"environment\" = \"Sandbox\";
\t\"pod\" = \"100\";
\t\"signing-status\" = \"0\";
}`)
in golang? or is there any better way to do that?
Double quotes and backticks denote different string literals in Go: https://play.golang.org/p/wfIPUJtxT9n
In particular, backslashes are not escape characters when used with backticks; they are preserved. For instance, len("\"") == 1
(byte 0x22), but len(`\"`) == 2
(bytes 0x5C and 0x22).
This is defined in the spec:
Raw string literals are character sequences between back quotes, as in
foo
. Within the quotes, any character may appear except back quote. The value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes; in particular, backslashes have no special meaning and the string may contain newlines. Carriage return characters ('') inside raw string literals are discarded from the raw string value.