首页 > 解决方案 > json.Marshal 用于带有 echo 的 http post 请求

问题描述

我有两个在 localhost 上运行的 golang 服务器。

他们使用不同的端口。

我想在一个向另一个发送 JSON 对象的请求上创建一个发布请求。

我正在使用 echo 框架(如果这很重要)

我得到的错误是当我尝试为 post 对象编组对象时:

2-valued json.Marshal(data) (value of type ([]byte, error)) where single value is expected

服务器 1:

type SendEmail struct {
    SenderName       string `json:"senderName,omitempty" bson:"senderName,omitempty" validate:"required,min=3,max=128"`
    SenderEmail      string `json:"senderEmail" bson:"senderEmail" validate:"required,min=10,max=128"`
    Subject          string `json:"subject" bson:"subject" validate:"required,min=10,max=128"`
    RecipientName    string `json:"recipientName" bson:"recipientName" validate:"required,min=3,max=128"`
    RecipientEmail   string `json:"recipientEmail" bson:"recipientEmail" validate:"required,min=10,max=128"`
    PlainTextContent string `json:"plainTextContent" bson:"plainTextContent" validate:"required,min=10,max=512"`
}

func resetPassword(c echo.Context) error {

email := c.Param("email")
    if email == "" {
        return c.String(http.StatusNotFound, "You have not supplied a valid email")
    }

    data := SendEmail{
        RecipientEmail:   email,
        RecipientName:    email,
        SenderEmail:      “test@test”,
        SenderName:       “name”,
        Subject:          "Reset Password",
        PlainTextContent: "Here is your code to reset your password, if you did not request this email then please ignore.",

    }

// error here
    req, err := http.NewRequest("POST", "127.0.0.1:8081/", json.Marshal(data))

    if err != nil {
        fmt.Println(err)
    }
    defer req.Body.Close()

    return c.JSON(http.StatusOK, email)
}

服务器 2:

e.GET("/", defaultRoute)

func defaultRoute(c echo.Context) (err error) {


    u := SendEmail{}
    if err = c.Bind(u); err != nil {
        return
    }

    return c.JSON(http.StatusOK, u)
}

标签: go

解决方案


json.Marshal返回[]byteerror这意味着您将 4 个值传递给http.NewRequest.

您应该json.Marshal先调用,然后将结果用于http.NewRequest.

body, err := json.Marshal(data)
if err != nil {
 // deal with error
}
req, err := http.NewRequest("POST", "127.0.0.1:8081/", body)

推荐阅读