Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling errors from base64 decode in Go

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("\nbase64 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?

like image 804
evilSnobu Avatar asked May 01 '26 11:05

evilSnobu


1 Answers

Look at the error type. For example,

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    encoded := "XXXXXaGVsbG8=" // corrupt
    decoded, err := base64.StdEncoding.DecodeString(encoded)
    if err != nil {
        if _, ok := err.(base64.CorruptInputError); ok {
            panic("\nbase64 input is corrupt, check service Key")
        }
        panic(err)
    }
    fmt.Println(string(decoded))
}

Output:

panic: 
base64 input is corrupt, check service Key
like image 167
peterSO Avatar answered May 03 '26 03:05

peterSO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!