簡體   English   中英

如何在 go Fiber 框架中獲取請求正文

[英]How to get Request body in go Fiber framework

我正在嘗試使用 GO Fiber 框架來實現我的后端,但是我對如何在 GO 光纖上的 post 請求中獲取請求正文有點困惑,所以我可以為我的后端邏輯處理它。 請幫助我,因為我是 Fiber 框架和 GO 的新手。

我的 Go 光纖 controller function

// CreateTodo : Create a todo
func CreateFarm(c *fiber.Ctx) error {
    farmCollection := config.MI.DB.Collection(os.Getenv("FARM_COLLECTION"))
    
    data := new(models.Farms)
    log.Println("dasta", data)
    err := c.BodyParser(&data) <------ how to get request body 

    // if error
    if err != nil {
        return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
            "success": false,
            "message": "Cannot parse JSON",
            "error":   err,
        })
    }

    result, err := farmCollection.InsertOne(c.Context(), data)

    if err != nil {
        return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
            "success": false,
            "message": "Cannot insert todo",
            "error":   err,
        })
    }

    // get the inserted data
    farm := &models.Farms{}
    query := bson.D{{Key: "_id", Value: result.InsertedID}}

    farmCollection.FindOne(c.Context(), query).Decode(farm)

    return c.Status(fiber.StatusCreated).JSON(fiber.Map{
        "success": true,
        "message": "Farm Update successfully",

    })
}

我正在嘗試使用 GO Fiber 框架來實現我的后端,但是我對如何在 GO 光纖上的 post 請求中獲取請求正文有點困惑,所以我可以為我的后端邏輯處理它。 請幫助我,因為我是 Fiber 框架和 GO 的新手。

我的 Go 光纖 controller function

// CreateTodo : Create a todo
func CreateFarm(c *fiber.Ctx) error {
    farmCollection := config.MI.DB.Collection(os.Getenv("FARM_COLLECTION"))
    
    data := new(models.Farms)
    log.Println("dasta", data)
    err := c.BodyParser(&data) <------ how to get request body 

    // if error
    if err != nil {
        return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
            "success": false,
            "message": "Cannot parse JSON",
            "error":   err,
        })
    }

    result, err := farmCollection.InsertOne(c.Context(), data)

    if err != nil {
        return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
            "success": false,
            "message": "Cannot insert todo",
            "error":   err,
        })
    }

    // get the inserted data
    farm := &models.Farms{}
    query := bson.D{{Key: "_id", Value: result.InsertedID}}

    farmCollection.FindOne(c.Context(), query).Decode(farm)

    return c.Status(fiber.StatusCreated).JSON(fiber.Map{
        "success": true,
        "message": "Farm Update successfully",

    })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM