无法对json.decoded请求主体进行编码

问题描述 投票:-3回答:1

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

您正在编组为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

© www.soinside.com 2019 - 2024. All rights reserved.