小编Gai*_*rOS的帖子

使用 Echo 测试 POST 请求(预期输出与实际输出)

我对 Go 有点陌生,所以,如果这是一个愚蠢的问题,我很抱歉。

我最近一直在尝试使用 Echo 的一些 API。我正在尝试测试 Go echo 的路由(POST)处理程序,它获取 json 并将其放入数组中。下面是处理程序main.go和测试test_main.go的代码

main.go

type Houses struct {
Name    string `json:"name,ommitempty"`
Address string `json:"address,omitempty"`
}

var houses []Houses

func 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))
}
Run Code Online (Sandbox Code Playgroud)

test_main.go

import (
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"

    "github.com/labstack/echo" …
Run Code Online (Sandbox Code Playgroud)

post json go go-echo

5
推荐指数
1
解决办法
7961
查看次数

标签 统计

go ×1

go-echo ×1

json ×1

post ×1