2015-10-12 03:31
浏览 161


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 {
    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 {

    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.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongpengyu1363 2015-10-12 03:38

    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
    解决 无用
    打赏 举报

相关推荐 更多相似问题