duanpin2009 2017-07-02 10:53
浏览 764
已采纳

在Go中处理来自base64解码的错误

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?

  • 写回答

2条回答 默认 最新

  • douweng7083 2017-07-02 11:20
    关注

    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("
    base64 input is corrupt, check service Key")
            }
            panic(err)
        }
        fmt.Println(string(decoded))
    }
    

    Output:

    panic: 
    base64 input is corrupt, check service Key
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 access中怎么分割分别获取一下图中的值
  • ¥15 keras_tcn已经安装成功,还是显示ModuleNotFoundError: No module named 'keras_tcn'
  • ¥15 类图中关联与聚合的区别
  • ¥15 ENVI高分五号去除云层的方法
  • ¥15 16进制数据如何得到奇偶校验位
  • ¥15 求合并两个字节流VB6代码
  • ¥15 Pyqt 如何正确的关掉Qthread,并且释放其中的锁?
  • ¥30 网站服务器通过node.js部署了一个项目!前端访问失败
  • ¥15 WPS访问权限不足怎么解决
  • ¥15 java幂等控制问题