UTF8 Encode and Decode in GO Golang

0

I would like to know how I can apply the utf8 to a string in golang. Investigating in the documentation , do the following:

I am making a query to a database and in the field the following information is stored ANDRÉS NUÑEZ when making the query, in the variable ANDR�S NU�EZ is stored, after review, make the following code:

Variable structure:

type DataBD struct {
    ID       int
    Nom_User string
}

Connection to the DB:

db, err := sql.Open("odbc", "DSN=" + host)

Code Utf8:

str := Data.nombre
        for len(str) > 0 {
            r, size := utf8.DecodeRuneInString(str)
            log.Printf("%c %c\n", r, size)

            str = str[size:]
        }

But the result remains the same. I clarify that I am importing import "unicode/utf8" .

RESULT:

2018/05/29 08:48:55 A
2018/05/29 08:48:55 N
2018/05/29 08:48:55 D
2018/05/29 08:48:55 R
2018/05/29 08:48:55 �
2018/05/29 08:48:55 S
2018/05/29 08:48:55 
2018/05/29 08:48:55 N
2018/05/29 08:48:55 U
2018/05/29 08:48:55 �
2018/05/29 08:48:55 E
2018/05/29 08:48:55 Z
    
asked by Andrés 29.05.2018 в 15:50
source

2 answers

1

After investigating and investigating, I found the solution, I leave the source and the code in case someone is in the same situation:

-Code:

func utf8_decode(str string)string {    
    var result string
    for i := range str {
        result += string(str[i])
    }    
    return result
}

-Implementation:

DataBD.Nombre= utf8_decode(DataBD.Nombre)

I leave the source with which I could generate the answer:

link

    
answered by 29.05.2018 / 21:20
source
0

Golang has support for unicode as part of all its strings, for example:

What may be happening is that the database is not correctly transmitting the characters encoded in UTF-8. If the DB has special columns to store unicode strings such as varchar utf8_collate_ci in MySQL or nchar and nvarchar in case of MSSQL it's worth trying to change the type of the column before

If that does not work then one can try to force the conversion by changing the type of the record field where the results are stored, for example:

type registro {
  ID int
  Nombre []byte
}

func (r *registro) GetNombre() string {
    return string(r.Nombre)
}

Then use the value like this:

// "SELECT nombre FROM usuarios;"
// ... codigo que realiza consulta ...
for rows.Next() {
   reg := &registro{}
   if err := rows.Scan(&reg.Nombre); err != nil {
      // reportar error
   }

   fmt.Println("Nombre: ", reg.GetNombre())
}
    
answered by 29.05.2018 в 17:58