登录
首页 >  Golang >  Go问答

Write to JSON failed, please help to check.

来源:SegmentFault

时间:2023-01-08 21:22:42 488浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《Write to JSON failed, please help to check.》,聊聊go,我们一起来看看吧!

问题内容

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.

终于介绍完啦!小伙伴们,这篇关于《Write to JSON failed, please help to check.》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表