How to decode base64 string and get the correct characters including the accents?

2.1k Views Asked by At

I must decode with golang a string that contains words in Spanish, with accents and special characters. But what I have tried does not work. Could you please guide me on the right path, to get what I need. Thanks in advance. This is my current code:

import (
    "encoding/base64"
    "fmt"

    "golang.org/x/text/encoding/unicode"
)

    var authStr = "2m5pY2E6U+06e1v28V19Okludml0YWNp824="
    arB, _ := base64.StdEncoding.DecodeString(authStr)
    fmt.Println("De arB se obtuvo: ")
    fmt.Println(string(arB)) 
    // got->        �nica:S�:{[��]}:Invitaci�n
    // expected->   Única:Sí:{[öñ]}:Invitación
    dec := unicode.UTF8.NewDecoder()
    arButf8 := make([]byte, len(arB)*2)
    if n, _, err := dec.Transform(arButf8, []byte(arB), true); err != nil {
        fmt.Println("Error: ", err)
    } else {
        arButf8 = arButf8[:n]
        fmt.Println("De authStr se obtuvo: ")
        fmt.Println(string(arButf8)) 
        // got->        �nica:S�:{[��]}:Invitaci�n
        // expected->   Única:Sí:{[öñ]}:Invitación          
    }
    // If do with Javascript atob("2m5pY2E6U+06e1v28V19Okludml0YWNp824=") works fine
1

There are 1 best solutions below

0
On

This is the correct code:

    import (
     "encoding/base64"
     "fmt"
     "golang.org/x/text/encoding/charmap"
    )
    var authStr = "2m5pY2E6U+06e1v28V19Okludml0YWNp824="
    arB, _ := base64.StdEncoding.DecodeString(authStr)
    fmt.Println("De arB se obtuvo: ")
    fmt.Println(string(arB)) 
    dec := charmap.ISO8859_1.NewDecoder()
    arBdest := make([]byte, len(arB)*2)
    if n, _, err := dec.Transform(arBdest, []byte(arB), true); err != nil {
        fmt.Println("Error: ", err)
    } else {
        arBdest = arBdest[:n]
        fmt.Println("De authStr se obtuvo: ")
        fmt.Println(string(arBdest))         
    }