json - 没有 Json 返回

标签 json http go goroutine

我正在尝试使用 Go 例程将 Json 数据返回给请求。当我在没有“go”的情况下测试 1(w,r) 时,我的代码有效。当我将 test1() 用作 go 例程时,我没有取回任何 json 数据。为什么会这样?

func main() {

    http.HandleFunc("/test", viewdata)

    http.ListenAndServe(":8080", nil)
}

func viewdata(w http.ResponseWriter, r *http.Request) {

    go test1(w, r)

}

func test1(w http.ResponseWriter, r *http.Request) {

   // example struct
    ll := sample{
        "city",
        12,
    }

    w.Header().Set("Content-Type", "application/json")
    json, _ := json.Marshal(ll)
    w.Write(json)

}

最佳答案

根据您的代码流程,我看不出使用 goroutine 有什么意义。也许你有一些理由。

让我们开始您的问题。当前,您的请求在 viewdata 处理程序启动的 goroutine 之前完成。所以,你必须使用 sync.WaitGroup 来等待 goroutine test1 完成执行。

您的更新代码:

func viewdata(w http.ResponseWriter, r *http.Request) {
    var wg sync.WaitGroup
    wg.Add(1)
    go test1(w, r, &wg)
    wg.Wait()
}

func test1(w http.ResponseWriter, r *http.Request, wg *sync.WaitGroup) {
    defer wg.Done()

    ll := sample{
        "city",
        12,
    }

    w.Header().Set("Content-Type", "application/json")
    json, _ := json.Marshal(ll)
    w.Write(json)
}

关于json - 没有 Json 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45003457/

相关文章:

json - 在SenseNet设置中使用JSON数组

apache - 可以模拟 HTTP 协议(protocol)中的流量控制吗? (原始 HTTP 协议(protocol))

perl - HTTP::Tiny 类似 FTP 处理

python - 检查很多 URL 看看是否返回 200。最聪明的方法是什么?

go - 马提尼绑定(bind) "cannot return value obtained from unexported field or method"

Json Decode 无法将 json 中的时间戳解析为 Go 结构

java - 如何以正确/列出的顺序获取 JSONObject 值?

php - 将 PHP json 编码的 UTF8 字符串转换为常规字符

go - 如何在 Golang 中动态映射数据库表?

javascript - 使用 jQuery 提交表单(json 编码、ajax、解析原始 url/方法)