go - 无法编码 json.decoded 请求正文

标签 go

我有一个服务器实现。现在我正在编写单元测试来检查它的功能。
我无法准备请求,这将在服务器端很好地解码。下面的代码导致 InvalidUnmarshallError。我不知道,如何进一步调试它。

客户端代码:

    body := PatchCatRequest{Adopted: true}
    bodyBuf := &bytes.Buffer{}
    err := json.NewEncoder(bodyBuf).Encode(body)
    assert.NoError(t, err)
    req, err := http.NewRequest("PATCH", URL+"/"+catId, bodyBuf)
    recorder := httptest.NewRecorder()
    handler.PatchCat(recorder, req.WithContext(ctx))

服务器端代码:
type PatchCatRequest struct {
Adopted bool `json:"adopted"`
}

func (h *Handler) PatchCat (rw http.ResponseWriter, req *http.Request) {
    var patchRequest *PatchCatRequest


if err := json.NewDecoder(req.Body).Decode(patchRequest); err != nil {
    rw.WriteHeader(http.StatusBadRequest)
    logger.WithField("error", err.Error()).Error(ErrDocodeRequest.Error())
    return
}
...
}

最佳答案

正如错误消息所述,您正在解码为 nil 指针:

package main

import (
    "encoding/json"
    "fmt"
)

type PatchCatRequest struct {
    Adopted bool
}

func main() {
    var patchRequest *PatchCatRequest // nil pointer

    err := json.Unmarshal([]byte(`{"Adopted":true}`), patchRequest)
    fmt.Println(err) // json: Unmarshal(nil *main.PatchCatRequest)
}

https://play.golang.org/p/vt7t5BgT3lA

在解码之前初始化指针:
func main() {
    patchRequest := new(PatchCatRequest) // non-nil pointer

    err := json.Unmarshal([]byte(`{"Adopted":true}`), patchRequest)
    fmt.Println(err) // <nil>
}

https://play.golang.org/p/BqliguktWmr

关于go - 无法编码 json.decoded 请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59679694/

相关文章:

go - 如何约束Go的grpc go例程个数

go - 在golang中的字符或字符串之前从字符串中grep子字符串的最佳方法

go - 如何使用 golang 微服务?

go - 在 Golang 中找不到导入的包

function - 当函数是变量时重新运行当前函数

algorithm - 为什么这个 Golang 中的正确代码在 HackerRank 上被认为是错误的?

go - 使用无缓冲 channel 的并发问题

android - Android 上运行的 Go 程序如何访问互联网?

Golang协程错误 "all goroutines are asleep - deadlock!"

go - 从 Go 应用的 Dataflow 模板创建作业