我正在尝试使用 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/