go - 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)
}
解决方案
json.Marshal
返回[]byte
,error
这意味着您将 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)
推荐阅读
- amazon-web-services - 何时值得在 DynamoDB 中使用本地二级索引进行权衡?
- ruby - Python virtualenv中的Ruby HTTP Post请求在客户端非常慢
- java - 拉姆达表达式必须在方法内吗?它们可以作为类的成员存在于方法之外吗
- html - body 标签不占用所有窗口宽度 +1600px
- javascript - 使用 webworker 和 promise 处理异步函数
- css - 乘车预订屏幕的 CSS
- c# - Invalid cache key parameter specified when enabling caching for a path parameter in AWS API Gateway
- java - 为什么会出现错误:Netbeans 中的 java.lang.IllegalArgumentException 和 java.lang.reflect.InvocationTargetException?
- javascript - 导出/导入 React 组件的问题
- python - Telegram API:如何从 id (Python telepot) 获取用户名?