Encode/Decode base64

前端 未结 5 1011
陌清茗
陌清茗 2021-02-06 22:06

here is my code and i don\'t understand why the decode function doesn\'t work.

Little insight would be great please.

func EncodeB64(message string) (reto         


        
相关标签:
5条回答
  • 2021-02-06 22:33

    See this Example (code/decode base64):

    http://play.golang.org/p/t6rFm2x4Yr

    @firebitsbr

    0 讨论(0)
  • 2021-02-06 22:41

    The len prefix is superficial and causes the invalid utf-8 error:

    package main
    
    import (
            "encoding/base64"
            "fmt"
            "log"
    )
    
    func main() {
            str := base64.StdEncoding.EncodeToString([]byte("Hello, playground"))
            fmt.Println(str)
    
            data, err := base64.StdEncoding.DecodeString(str)
            if err != nil {
                    log.Fatal("error:", err)
            }
    
            fmt.Printf("%q\n", data)
    }
    

    (Also here)


    Output

    SGVsbG8sIHBsYXlncm91bmQ=
    "Hello, playground"
    

    EDIT: I read too fast, the len was not used as a prefix. dystroy got it right.

    0 讨论(0)
  • 2021-02-06 22:44

    DecodedLen returns the maximal length.

    This length is useful for sizing your buffer but part of the buffer won't be written and thus won't be valid UTF-8.

    You have to use only the real written length returned by the Decode function.

    l, _ := base64.StdEncoding.Decode(base64Text, []byte(message))
    log.Printf("base64: %s\n", base64Text[:l])
    
    0 讨论(0)
  • 2021-02-06 22:54

    To sum up the other two posts, here are two simple functions to encode/decode Base64 strings with Go:

    // Dont forget to import "encoding/base64"!
    
    func base64Encode(str string) string {
        return base64.StdEncoding.EncodeToString([]byte(str))
    }
    
    func base64Decode(str string) (string, bool) {
        data, err := base64.StdEncoding.DecodeString(str)
        if err != nil {
            return "", true
        }
        return string(data), false
    }
    

    Try it!

    0 讨论(0)
  • 2021-02-06 22:55

    @Denys Séguret's answer is almost 100% correct. As an improvement to avoid wasting memory with non used space in base64Text, you should use base64.DecodedLen. Take a look at how base64.DecodeString uses it. It should look like this:

    func main() {
        message := base64.StdEncoding.EncodeToString([]byte("Hello, playground"))
    
        base64Text := make([]byte, base64.StdEncoding.DecodedLen(len(message)))
    
        n, _ := base64.StdEncoding.Decode(base64Text, []byte(message))
        fmt.Println("base64Text:", string(base64Text[:n]))
    }
    

    Try it here.

    0 讨论(0)
提交回复
热议问题