首页 > Write to JSON failed, please help to check.

Write to JSON failed, please help to check.

package main

import (
    "database/sql"
    "github.com/ant0ine/go-json-rest/rest"
    _ "github.com/lib/pq"
    "log"
    "net/http"
)

func main() {

    api := rest.NewApi()
    api.Use(rest.DefaultDevStack...)
    router, err := rest.MakeRouter(
        rest.Get("/books", GetAllBooks),
    )
    if err != nil {
        log.Fatal(err)
    }
    api.SetApp(router)
    log.Fatal(http.ListenAndServe(":8000", api.MakeHandler()))
}

type Book struct {
    isbn   string  `json:"isbn"`
    title  string  `json:"title"`
    author string  `json:"author"`
    price  float32 `json:"price"`
}

var db *sql.DB

func init() {
    var err error
    db, err = sql.Open("postgres", "postgres://postgres:123456@localhost/test")
    if err != nil {
        log.Fatal(err)
    }

    if err = db.Ping(); err != nil {
        log.Fatal(err)
    }
}

func GetAllBooks(w rest.ResponseWriter, r *rest.Request) {
    rows, err := db.Query("SELECT * FROM books")
    if err != nil {
        rest.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer rows.Close()
    books := make([]Book, 10)
    for rows.Next() {
        var book Book
        err := rows.Scan(&book.isbn, &book.title, &book.author, &book.price)
        if err != nil {
            rest.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        books = append(books, book)
    }
    if err = rows.Err(); err != nil {
        rest.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    w.WriteJson(books)
}

Output:
[
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{}
]

Database table records:

      isbn      |      title       |       author        | price
----------------+------------------+---------------------+-------
 978-1503261969 | Emma             | Jayne Austen        |  9.44
 978-1505255607 | The Time Machine | H. G. Wells         |  5.99
 978-1503379640 | The Prince       | Niccolò Machiavelli |  6.99
 978-1470184842 | Metamorphosis    | Franz Kafka         |  5.90
(4 rows)

Question: Not sure why the output is always empty, someone could help?


The json package only accesses the exported fields of struct types (those that begin with an uppercase letter). Therefore only the the exported fields of a struct will be present in the JSON output.

【热门文章】
【热门文章】