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

4

1 回答 1

2

出现错误是因为您使用 structPartage创建对象,但尚未声明它。

type Partage struct {
    user_id string
    nama string
}

但是如何将结果显示为 JSON 响应?我试过 r.JSON(200, partages) 但没有显示结果

马提尼中,您可以使用JSON 格式r.JSON()打印rows

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

    r.JSON(200, map[string]interface{}{
        data: rows
    })
})
于 2015-10-12T03:38:39.180 回答