Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON response in Golang’s GIN returning as scrambled data

Tags:

json

go

go-gin

I have array of a struct being created from data I collected from the database.

For simplicity, lets say this is the struct:

type Person struct {
ID        int    `db:"id, json:"id"`
}

type PessoalController struct{}

func (ctrl PessoalController) GetPessoal(c *gin.Context) { 
    q := "select id from rh"

    rows, err := db.GetDB().Query(q)
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    var pessoas []Pessoal

    var id
    for rows.Next() {
        err := rows.Scan(&id)
        if err != nil {
            log.Fatal(err)
    }
    pessoas = append(pessoas, Pessoal{ ID: id,})

    JsonPessoal, errr := json.Marshal(pessoas)
    if errr != nil {
        log.Fatal(err)
    }
    c.JSON(200, pessoas)
    if err != nil {
        return
    }

    return
}

When I print it, I do get the JSON I expected. But when I send the response, I get raw-looking data like “W3siWQiQjlyNDYslNpYx...”

Have no idea how to proceed.

Edit : Minimal, Complete, and Verifiable example.

like image 730
Auyer Avatar asked Dec 28 '17 16:12

Auyer


People also ask

What is gin Default ()?

gin. Default() creates a Gin router with default middleware: logger and recovery middleware. Next, we make a handler using router. GET(path, handle) , where path is the relative path,​ and handle is the handler function that takes *gin. Context as an argument.

What is * gin context?

The gin Context is a structure that contains both the http. Request and the http. Response that a normal http. Handler would use, plus some useful methods and shortcuts to manipulate those. The gin engine is responsible for the creation (and reuse) of those contexts, in the same manner as the http.

What is gin Handlerfunc?

Gin is a web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster thanks to httprouter.

What is gin engine?

Made by master distillers in the Alta Langa region of northwestern Italy, Engine Gin is a handcrafted London Dry gin. Its formula is linked to the Piedmontese tradition of Rosolio. It is a type of cordial made from sage and lemon that was used as a natural digestive in the past.


2 Answers

c.JSON is serializing into JSON, so you should be doing:

c.JSON(200, pessoas)
like image 145
dave Avatar answered Sep 23 '22 07:09

dave


Your codes ans the question itself. Look at it and read my comments in the code.

jsonPessoal, errr := json.Marshal(pessoas)
if errr != nil {
    log.Fatal(err)
}
fmt.Fprintf(os.Stdout, "%s", jsonPessoal) // still fine here .
// it is fine because you are formating []byte into string using fmt and 
// printing it on console. `%s` makes sures that it echos as string. 

c.JSON(200, jsonPessoal ) // jsonPessoal is still a []byte !! 
if err != nil {
    return
}

The correct way to echo json string using gin would be

c.JSON(http.StatusOK, gin.H{ 
            "code" : http.StatusOK, 
            "message": string(jsonPessoal),// cast it to string before showing
})
like image 44
sh0umik Avatar answered Sep 20 '22 07:09

sh0umik