Go 无法对json.decoded请求正文进行编码
我有一个服务器实现。现在我正在编写单元测试来检查它的功能。 我无法准备请求,这将在服务器端很好地解组。以下代码导致InvalidUnmarshall错误。我不知道如何进一步调试它 客户端代码:Go 无法对json.decoded请求正文进行编码,go,Go,我有一个服务器实现。现在我正在编写单元测试来检查它的功能。 我无法准备请求,这将在服务器端很好地解组。以下代码导致InvalidUnmarshall错误。我不知道如何进一步调试它 客户端代码: body := PatchCatRequest{Adopted: true} bodyBuf := &bytes.Buffer{} err := json.NewEncoder(bodyBuf).Encode(body) assert.NoError(t, err)
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
}
...
}
服务器端代码:
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)
}
在解组之前初始化指针:
func main() {
patchRequest := new(PatchCatRequest) // non-nil pointer
err := json.Unmarshal([]byte(`{"Adopted":true}`), patchRequest)
fmt.Println(err) // <nil>
}
func main(){
patchRequest:=新建(PatchCatRequest)//非零指针
err:=json.Unmarshal([]字节(`{“已采用”:true}`),patchRequest)
fmt.Println(错误)//
}
如果您遇到错误,请在问题中包含错误。
InvalidUnmarshallError