Error:
panic: runtime error: index out of range
goroutine 1 [running]:
encoding/base64.(*Encoding).Encode(0xc420056000, 0x0, 0x0, 0x0, 0xc42003bf30, 0xe, 0x20)
/usr/lib/go/src/encoding/base64/base64.go:113 +0x27b
main.main()
/home/martin/a.go:11 +0x9b
exit status 2
shell returned 1
If we look at line /usr/lib/go/src/encoding/base64/base64.go113, we will see (abbreviated):
n := (len(src) / 3) * 3
for si < n {
dst[di+0] = enc.encode[val>>18&0x3F]
dst[di+0] = enc.encode[val>>18&0x3F]
dst[di+1] = enc.encode[val>>12&0x3F]
}
In other words, this function sets the index directly dst. The length var encodedData []byteis zero, so you get an error index out of range.
One way to fix this is to change the line to:
encodedData := make([]byte, base64.StdEncoding.EncodedLen(len(data)))
. Base64 , , base64.StdEncoding.EncodedLen().
. :
. NewEncoder().
NewEncoder() :
func main() {
data := []byte("string of data")
encodedData := &bytes.Buffer{}
encoder := base64.NewEncoder(base64.StdEncoding, encodedData)
defer encoder.Close()
encoder.Write(data)
fmt.Println(encodedData)
}
, EncodeToString(), : encodedData := base64.StdEncoding.EncodeToString(data).