请求体未到达 Golang Fiber。

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

The request body does not reach golang fiber

问题

当我发送一个POST请求时,服务器没有接收到请求体,只有id被添加到数据库中。

package lists

import (
	"github.com/fishkaoff/fiber-todo-list/pkg/common/models"

	"github.com/gofiber/fiber/v2"
)

type AddTaskRequestBody struct {
	title       string `json:"title"`
	description string `json:"description"`
}

func (h handler) Addtask(c *fiber.Ctx) error {
	body := AddTaskRequestBody{}

	if err := c.BodyParser(&body); err != nil {
		return fiber.NewError(fiber.StatusBadRequest, err.Error())
	}

	title := body.title
	description := body.title
	if title == "" || description == "" {
		return fiber.NewError(fiber.StatusBadRequest)
	}
	task := models.NewList(title, description)

	if result := h.DB.Create(&task); result.Error != nil {
		return fiber.NewError(fiber.StatusNotFound)
	}
	return c.Status(fiber.StatusCreated).JSON(&task)
}

Postman请求:
点击这里查看图片

英文:

When I send a POST request, the server does not receive the request body. Only the id is added to the database

"package lists

import (
"github.com/fishkaoff/fiber-todo-list/pkg/common/models"

"github.com/gofiber/fiber/v2"
)

type AddTaskRequestBody struct {
    title string `json:"title"`
    description string `json:"description"`
}

func (h handler) Addtask(c *fiber.Ctx) error {
    body := AddTaskRequestBody{}

    if err := c.BodyParser(&body); err != nil {
	    return fiber.NewError(fiber.StatusBadRequest, err.Error())
    }

    title := body.title
    description := body.title
    if title == "" || description == "" {
	    return fiber.NewError(fiber.StatusBadRequest)
    }
    task := models.NewList(title, description)

    if result := h.DB.Create(&task); result.Error != nil {
	    return fiber.NewError(fiber.StatusNotFound, 
    }
    return c.Status(fiber.StatusCreated).JSON(&task)
}"

postman request:
enter image description here

答案1

得分: 0

结构体AddTaskRequestBody的字段没有被导出,这可能是问题所在。title和description应该是大写的。参考链接:https://golangbyexample.com/exported-unexported-fields-struct-go/

type AddTaskRequestBody struct {
Title string json:"title"
Description string json:"description"
}

英文:

the fields of the structure AddTaskRequestBody are not being exported. That may be the problem. Shouldn't title and description be uppercase - (https://golangbyexample.com/exported-unexported-fields-struct-go/)

type AddTaskRequestBody struct {
title string json:"title"
description string json:"description"
}

huangapple
  • 本文由 发表于 2022年8月19日 05:16:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/73409527.html
匿名

发表评论

匿名网友

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

确定