我是 Go 的新手,所以,如果這是一個愚蠢的問題,我很抱歉。我最近一直在嘗試使用 Echo 的一些 API。我正在嘗試測試獲取 json 并將其放入數組中的 Go echo 的路由(POST)處理程序。下面是處理程序main.go和測試test_main.go的代碼main.gotype Houses struct {Name string `json:"name,ommitempty"`Address string `json:"address,omitempty"`}var houses []Housesfunc newHouse(c echo.Context) error { m := echo.Map{} if err := c.Bind(&m); err != nil { return err } dv := Houses{ Name: m["name"].(string), Address: m["address"].(string), } houses = append(houses, dv) js, _ := json.Marshal(houses) fmt.Println(fmt.Sprintf("%s", js)) return c.JSON(http.StatusOK, string(js))}test_main.goimport ( "net/http" "net/http/httptest" "strings" "testing" "github.com/labstack/echo" "github.com/stretchr/testify/assert")var userJSON = `{"name":"Jhon Doe","address":"High St."}`func TestModel(t *testing.T) { url := "/new_house" e := echo.New() req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(userJSON)) req.Header.Set("Content-Type", "application/json") if err != nil { t.Errorf("The request could not be created because of: %v", err) } rec := httptest.NewRecorder() c := e.NewContext(req, rec) // c.SetPath("/new_house") // c.JSON(http.StatusOK, Devices{"Jhon Doe", "Middle Way"}) res := rec.Result() defer res.Body.Close() if assert.NoError(t, newHouse(c)) { assert.Equal(t, http.StatusOK, rec.Code) assert.Equal(t, "["+userJSON+"]", rec.Body.String()) }}即使通過 curl 調用處理程序正常工作,測試也會失敗并顯示如下錯誤。經過幾天的努力,我無法弄清楚如何使實際輸出符合預期,所以我在這里發帖希望能克服這個障礙。任何幫助表示贊賞!
1 回答

慕桂英4014372
TA貢獻1871條經驗 獲得超13個贊
您正在調用json.Marshal
,[]Houses
它將其編組為 JSON 字符串,然后您echo.Context.JSON
使用 JSON 字符串進行調用,它在內部調用json.Marshal
. 雙重編組導致轉義。參見示例。(為簡潔起見省略了錯誤檢查)
https://play.golang.org/p/nYvHS4huy0M
h := &Houses{"Jhon Doe", "High St."}
d, _ := json.Marshal(h)
// double marshal bad
d, _ = json.Marshal(string(d))
fmt.Println(string(d))
// prints "{\"name\":\"Jhon Doe\",\"address\":\"High St.\"}"
您的解決方案是將切片傳遞給您的c.JSON電話。作為旁注,您應該能夠將結構傳遞給c.Bind而不是使用帶有類型斷言的映射。
- 1 回答
- 0 關注
- 235 瀏覽
添加回答
舉報
0/150
提交
取消