-1

Recently, I'm learning about Go (Golang). I'm trying to make a simple web service using Martini and jwt-go. I didn't find any difficulty in retrieving a single row data and put in JSON as the response. But, when dealing with multiple-rows, it's a whole different story. Basically, I refer to the accepted answer here.

Here is the piece of my code:

m.Get("/users", func(params martini.Params, r render.Render) {
    db, err := sql.Open("mysql", "root:@/sirat_v2")
    if err != nil {
        panic(err.Error())
    }
    defer db.Close()

    rows, err := db.Query("SELECT user_id, nama FROM `users` WHERE password = ?", "asdfasdf")
    defer rows.Close()

    cols, err := rows.Columns()
    if err != nil {
        panic(err.Error())
    }

    partages := make([]*Partage, 0, 10)
    var user_id int
    var nama string
    for rows.Next() {
        err = rows.Scan(&user_id, &nama)
        if err != nil { /* error handling */
        }
        partages = append(partages, &Partage{user_id, nama})
    }
})

When trying to build, there's an error said that Partage is undefined.

Grokify
  • 15,092
  • 6
  • 60
  • 81
asubanovsky
  • 1,608
  • 3
  • 19
  • 36

1 Answers1

2

The error showing up because you use struct Partage to create an object, but you haven't declared it.

type Partage struct {
    user_id string
    nama string
}

But how do I display the result as JSON response? I've tried r.JSON(200, partages) but the results aren't displayed

In martini you can use r.JSON() to print rows as JSON

m.Get("/users", func(params martini.Params, r render.Render) {
    // ... 

    r.JSON(200, map[string]interface{}{
        data: rows
    })
})
novalagung
  • 10,905
  • 4
  • 58
  • 82
  • Thanks for the answer, Mas Noval (I'm from Indonesia too). But how do I display the result as JSON response? I've tried r.JSON(200, partages) but the results aren't displayed. – asubanovsky Oct 12 '15 at 03:45
  • Well implemented. Thank you very much. You save my day. – asubanovsky Oct 12 '15 at 04:16