gin-gonic的JSON转换输出返回空数组

huangapple go评论86阅读模式
英文:

gin-gonic json conversion output throws empty array

问题

以下是您提供的Go语言程序的翻译:

package main

import (
	"database/sql"
	"os"

	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
)

func index(c *gin.Context) {
	hostname, err := os.Hostname()
	checkErr(err)
	c.String(200, "v3 "+hostname)
}

func healthz(c *gin.Context) {
	c.String(200, "OK")
}

type InventoryItem struct {
	id                 int
	productID          string
	productCost        int
	productAvailabilty int
	productSubcat      string
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

/*******************  MAIN Function **************/
func main() {
	app := gin.Default()
	app.GET("/", index)
	app.GET("/healthz", healthz)
	app.GET("/inventory", fetch)
	app.Run(":8000")
}

/******************* End MAIN Function **************/

func fetch(c *gin.Context) {
	var (
		invt      InventoryItem
		inventory []InventoryItem
	)
	connStr := os.Getenv("sql_user") + ":" + os.Getenv("sql_password") + "@tcp(" + os.Getenv("sql_host") + ":3306)/" + os.Getenv("sql_db")
	db, err := sql.Open("mysql", connStr)
	checkErr(err)
	defer db.Close()
	rows, err := db.Query("SELECT id,product_id as productID,product_cost as productCost,product_availabilty as productAvailabilty,product_subcat as productSubcat FROM inventory;")
	for rows.Next() {
		err = rows.Scan(&invt.id, &invt.productID, &invt.productCost, &invt.productAvailabilty, &invt.productSubcat)
		checkErr(err)
		inventory = append(inventory, invt)
	}

	checkErr(err)
	defer rows.Close()
	//fmt.Print(inventory[0].productAvailabilty)
	c.JSON(200, inventory)
}

这段代码使用了gin-gonic库来创建一个基本的Web服务器。在fetch函数中,它从MySQL数据库中检索了一些库存数据,并将其作为JSON响应返回给客户端。如果您在调用c.JSON(200, inventory)时得到了空数组的输出,可能是因为数据库中没有匹配的数据。请确保数据库中有正确的数据,并且连接字符串和查询语句都是正确的。

英文:

for the following golang program, i'm not able to get json output using gin-gonic library, if i do fmt.Print variable shows values, but when i convert to c.JSON (inventory) out it shows empty array, what is wrong with my code?

   package main
import (
"database/sql"
"os"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
)
func index(c *gin.Context) {
hostname, err := os.Hostname()
checkErr(err)
c.String(200, "v3 "+hostname)
}
func healthz(c *gin.Context) {
c.String(200, "OK")
}
type InventoryItem struct {
id                 int
productID          string
productCost        int
productAvailabilty int
productSubcat      string
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
/*******************  MAIN Function **************/
func main() {
app := gin.Default()
app.GET("/", index)
app.GET("/healthz", healthz)
app.GET("/inventory", fetch)
app.Run(":8000")
}
/******************* End MAIN Function **************/
func fetch(c *gin.Context) {
var (
invt      InventoryItem
inventory []InventoryItem
)
connStr := os.Getenv("sql_user") + ":" + os.Getenv("sql_password") + "@tcp(" + os.Getenv("sql_host") + ":3306)/" + os.Getenv("sql_db")
db, err := sql.Open("mysql", connStr)
checkErr(err)
defer db.Close()
rows, err := db.Query("SELECT id,product_id as productID,product_cost as productCost,product_availabilty as productAvailabilty,product_subcat as productSubcat FROM inventory;")
for rows.Next() {
err = rows.Scan(&invt.id, &invt.productID, &invt.productCost, &invt.productAvailabilty, &invt.productSubcat)
checkErr(err)
inventory = append(inventory, invt)
}
checkErr(err)
defer rows.Close()
//fmt.Print(inventory[0].productAvailabilty)
c.JSON(200, inventory)
}

答案1

得分: 4

问题是InventoryItem结构体的字段必须是可导出的 -

type InventoryItem struct {
ID                 int    `json:"id"`
ProductID          string `json:"product_id"`
ProductCost        int    `json:"product_cost"`
ProductAvailabilty int    `json:"product_availability"`
ProductSubcat      string `json:"product_subact"`
}

了解更多关于导出和未导出字段的信息。

英文:

Issue is InventoryItem struct fields have to be exported -

type InventoryItem struct {
ID                 int    `json:"id"`
ProductID          string `json:"product_id"`
ProductCost        int    `json:"product_cost"`
ProductAvailabilty int    `json:"product_availability"`
ProductSubcat      string `json:"product_subact"`
}

Read more about exported and un-exported fields.

huangapple
  • 本文由 发表于 2017年6月18日 12:14:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/44611696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定