我尝试从Go接收数据,但是在浏览器中,我只收到一个hello world,也不错:)但是我需要一个对象->如您所见,我在后端使用了CORB规则还可以看到我的对象数组在打印功能。 请帮助在浏览器中获取数据,如果我仅将json设置为输出,则将成功。 请帮助了解我在做什么错 除了HTTP路由器的Gin方法外,请不要提供其他信息。如您所见,我必须重写BindJson函数,因为没有它,它将收到400错误
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"localDbExample/config"
"localDbExample/entities"
"localDbExample/models"
"net/http"
)
var router *gin.Engine
func BindJSON(c *gin.Context, obj interface{}) error {
if err := binding.JSON.Bind(c.Request, obj); err != nil {
c.Error(err).SetType(gin.ErrorTypeBind)
return err
}
return nil
}
func main() {
router = gin.Default()
initializeRoutes()
router.Run()
}
func Demo1_CallFindAll()(products []entities.Product) {
db,err:=config.GetMySQLDB()
if err !=nil{
fmt.Println(err)
}else{
productModel := models.ProductModel{
Db:db,
}
products,err := productModel.FindAll()
if err !=nil{
fmt.Println(err)
}else{
fmt.Println(products)
fmt.Println("Product List")
}
}
return products
}
func initializeRoutes() {
router.POST("/api", handleVerification)
router.OPTIONS("/api", handleVerification)
}
func handleVerification(c *gin.Context) {
if c.Request.Method == "OPTIONS" {
// setup headers
c.Header("Allow", "POST, GET, OPTIONS")
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "origin, content-type, accept")
c.Header("Content-Type", "application/json")
c.JSON(http.StatusOK, gin.H{"hello": "world"})
c.Status(http.StatusOK)
} else if c.Request.Method == "POST" {
c.Header("Allow", "POST, GET, OPTIONS")
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "origin, content-type, accept")
c.Header("Content-Type", "application/json")
var tags = Demo1_CallFindAll()
fmt.Println(tags)// [{1 Nokia1 10 2 true} {2 Nokia2 11 22 false}]
BindJSON(c,&tags)
c.JSON(http.StatusOK , gin.H{"hello": "world"})
}
}