Consider this simple base64 decode snippet:
package main
import (
"fmt"
"encoding/base64"
)
func main() {
const encoded string = "aGVsbG8=" // hello
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
panic(err)
}
fmt.Println(string(decoded))
}
This produces hello as expected. Now, if i intentionally pass in corrupt input, e.g.
const encoded string = "XXXXXaGVsbG8="
then i hit the panic line which gives me:
panic: illegal base64 data at input byte 11
goroutine 1 [running]:
main.main()
/tmp/sandbox422941756/main.go:12 +0x140
Looking at the source code and this issue, seems there is not much to go by here other than matching the string literal and returning a more meaningful error message to the caller:
if err != nil {
if strings.Contains(err.Error(), "illegal base64 data at input byte") {
panic("
base64 input is corrupt, check service Key")
}
}
There has to be a more elegant way to do this other than string matching. What is the go-esque way to achieve this?