簡體   English   中英

如何解碼base64字符串並獲得正確的字符(包括重音符號)?

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

我必須使用golang解碼一個包含西班牙語單詞,重音和特殊字符的字符串。 但是我嘗試過的方法不起作用。 您能否指導我走正確的道路,以獲得我所需要的東西。 提前致謝。 這是我當前的代碼:

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

這是正確的代碼:

    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))         
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM