Write to JSON failed, please help to check.
时间:2023-01-08
浏览: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相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
11.27
11.27
11.27
热门专题
