无法编码json.decoded请求主体

Marcin Ginszt:

我有一个服务器实现。现在,我正在编写单元测试以检查其功能。我无法准备请求,这会很好地在服务器端解组。以下代码导致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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章