dongxie559554 2018-10-19 09:12
浏览 841
已采纳

base64解码,然后json解码:base64.NewDecoder EOF错误和json无效字符错误

I'm trying to base64 decode HTTP request, then decode it using JSON decoder.

I tried two ways to implement base64 decoder:

func decode(encoded []byte) ([]byte, error) {
    buff := new(bytes.Buffer)
    decoder := base64.NewDecoder(base64.StdEncoding, buff)
    _, err := decoder.Read(encoded)

    return buff.Bytes(), err
}

This function returns an EOF error. Go playground link: https://play.golang.org/p/038rEXWYW6q


func decode(encoded []byte) ([]byte, error) {
    decoded := make([]byte, base64.StdEncoding.EncodedLen(len(encoded)))
    _, err := base64.StdEncoding.Decode(decoded, encoded)
    return decoded, err
}

This works but has extra x\00 characters so when decoding JSON we would have invalid character '\x00' after top-level value error.

Where is the problem with the first strategy?

  • 写回答

1条回答 默认 最新

  • douliaotong4944 2018-10-19 09:25
    关注

    In your code:

    You are creating a new buffer and assigning it to buff, since you have not given any source of input for it, it is empty.

    buff := new(bytes.Buffer)
    

    and NewDecoder is reading from empty buff. Like everything in go, if you want to create a something new, you should use it's constructor which always starts with package.Newxxx

    bytes.NewBuffer(src)
    

    Then decoder is a variable which contains the actual decoded data, and it has a reader interface(Read method). So you can pass it to method which accepts reader interface, and ioutil.ReadAll() is one of them.

    Added comments where ever necessary:

    package main
    
    import (
        "bytes"
        "encoding/base64"
        "fmt"
        "io/ioutil"
        "log"
    )
    
    // encoded data
    var data = "eyJhY3Rpdml0aWVzIjpbXSwic3VjY2VzcyI6ZmFsc2UsImNvZGUiOjk5OTl9"
    
    func main() {
        dec, err := decode([]byte(data))
        if err != nil {
            log.Println(err)
        }
        fmt.Println(string(dec)) // print returned value
    }
    
    func decode(enc []byte) ([]byte, error) {
        // create new buffer from enc
        // you can also use bytes.NewBuffer(enc)
        r := bytes.NewReader(enc)
        // pass it to NewDecoder so that it can read data
        dec := base64.NewDecoder(base64.StdEncoding, r)
        // read decoded data from dec to res
        res, err := ioutil.ReadAll(dec)
        return res, err
    }
    

    Infact the whole thing can be written in one line:

    func decode(enc []byte) ([]byte, error) {
        return ioutil.ReadAll(base64.NewDecoder(base64.StdEncoding, bytes.NewReader(enc)))
    }
    

    Output:

    {"activities":[],"success":false,"code":9999}
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部