Go语言 我的API无法使用Gin Context插入值

lokaqttq  于 2023-03-27  发布在  Go
关注(0)|答案(1)|浏览(132)

你能帮助我或告诉我什么错了我的代码。我试图使API与GIN框架。这是数据和后API的例子

type Car struct {
    CarID string `json:"car_id"`
    Brand string `json:"brand"`
    Model string `json:"model"`
    Price int    `json:"price"`
}

var CarDatas = []Car{}

func CreateCar(ctx *gin.Context) {
    var newCar Car

    if err := ctx.ShouldBindJSON(&newCar); err != nil {
        ctx.AbortWithError(http.StatusBadRequest, err)
        return
    }

    newCar.CarID = fmt.Sprintf("c%d", len(CarDatas)+1)
    CarDatas = append(CarDatas, newCar)

    ctx.JSON(http.StatusCreated, gin.H{
        "car": newCar,
    })
}

这是我的端点路由

func StartServer() *gin.Engine {
    router := gin.Default()

    router.POST("/cars", controllers.CreateCar)

    router.PUT("/cars/:carID", controllers.UpdateCar)

    router.GET("cars/:carID", controllers.GetCar)

    router.DELETE("cars/:carID", controllers.DeleteCar)
    return router
}

我的问题我的代码仍然坏请求时插入一个数据。不响应只是试图POST
你有什么线索吗?谢谢你的时间和答案

我已经检查和修复格式化,并没有真正的工作。请指导我或给予我一个线索

eivnm1vs

eivnm1vs1#

如果你在前端使用form-data,那么尝试在Gin中使用以下内容。

if err := c.Bind(&newCar); err != nil {
.....
}

ShouldBindJson应该用于json post请求。

相关问题