我的API无法在Gin Context中插入值。

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

My API can't insert value with Gin Context

问题

你好!根据你提供的代码和描述,我看到你在使用GIN框架创建API时遇到了问题。你的代码中有一些错误,我将为你指出并提供一些建议。

首先,你的结构体标签中的引号应该使用双引号而不是HTML实体编码。所以你的结构体应该像这样:

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

其次,在你的CreateCar函数中,你应该使用ctx.JSON来返回JSON响应,而不是ctx.AbortWithError。所以你的代码应该像这样:

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

	if err := ctx.ShouldBindJSON(&newCar); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		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
}

希望这些修改能帮助你解决问题。如果你还有其他问题,请随时提问!

英文:

Could you help me or inform me what wrong with my code. I tried to make API for with GIN Framework. This is example of data and Post 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,
	})
}

This is my endpoint routes

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
}

My question my code still bad request when insert a data. not respond just trying to POST

Do you have any clue?
Thanks for your time and the answer

我的API无法在Gin Context中插入值。

I already check and fix formating and not really work. Please just guide me or give me a clue

答案1

得分: 2

你在前端使用了form-data,那么在Gin框架中可以尝试使用以下代码:

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

对于JSON的POST请求,应该使用ShouldBindJSON方法。

英文:

you using form-data on front end, then try using the following in Gin.

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

ShouldBindJson should be used for json post requests.

huangapple
  • 本文由 发表于 2023年3月22日 20:14:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75812127.html
匿名

发表评论

匿名网友

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

确定