What is the best way to split a one line base64 into multiple lines by 76 chars. Currently I use encoding/base64
package as this:
encoded := base64.StdEncoding.EncodeToString(data)
Thank you in advance!
What is the best way to split a one line base64 into multiple lines by 76 chars. Currently I use encoding/base64
package as this:
encoded := base64.StdEncoding.EncodeToString(data)
Thank you in advance!
There is no support for this in the standard lib. You have to make one yourself.
A simple implementation can be like this:
func split(s string, size int) []string {
ss := make([]string, 0, len(s)/size+1)
for len(s) > 0 {
if len(s) < size {
size = len(s)
}
ss, s = append(ss, s[:size]), s[size:]
}
return ss
}
This loops until the string is consumed, and in each iteration cuts of size
chars (bytes) from the beginning.
Note that this works on base64 texts as that only uses characters which map 1-to-1 to bytes in the UTF-8 encoded form (which is how Go stores strings in memory). If you would want to use this on arbitrary strings, slicing could break valid UTF-8 sequences, and also chunks would not necessarily be size
characters.
Testing it:
s := strings.Repeat("1", 2*76+3)
for _, chunk := range split(s, 76) {
fmt.Println(chunk)
}
Output (try it on the Go Playground):
1111111111111111111111111111111111111111111111111111111111111111111111111111
1111111111111111111111111111111111111111111111111111111111111111111111111111
111