2 回答
TA贡献1796条经验 获得超4个赞
是的,您可以sync.WaitGroup按如下方式使用:
wg := sync.WaitGroup{}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
wg.Add(1) // add a waitgroup before calling the async function
player.Exec(command, func(response map[string]interface{}){
defer wg.Done() // release when this function returns
if response["statusCode"]==float64(0) { // ok
w.Write([]byte(response["statusMessage"].(string)))
player.SendMessage("<b>"+response["statusMessage"].(string)+"</b>")
fmt.Println("playerExec: "+time.Now().Format("20060102150405"))
} else { // failed to process
w.WriteHeader(http.StatusBadRequest) // 400
w.Write([]byte(response["statusMessage"].(string)))
player.SendMessage(response["statusMessage"].(string))
}
})
wg.Wait() // this will block until all the resources are released
fmt.Println("cmd: "+time.Now().Format("20060102150405"))
})
TA贡献1841条经验 获得超3个赞
http:来自 main.main.func1.1 的多余 response.WriteHeader 调用
如果您WriteHeader在通过Write. 这就是为什么 WriteHeader 是额外的或superfluous.
在等待你的 exec 完成时,你可以在你的闭包中使用 waitgroup 。
wg.Wait()将等到您的 exec 回调返回
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var wg sync.WaitGroup
wg.Add(1)
player.Exec(command, func(response map[string]interface{}){
defer wg.Done()
if response["statusCode"]==float64(0) { // ok
w.Write([]byte(response["statusMessage"].(string)))
player.SendMessage("<b>"+response["statusMessage"].(string)+"</b>")
fmt.Println("playerExec: "+time.Now().Format("20060102150405"))
} else { // failed to process
w.WriteHeader(http.StatusBadRequest) // 400
w.Write([]byte(response["statusMessage"].(string)))
player.SendMessage(response["statusMessage"].(string))
}
})
wg.Wait()
// Time.Sleep(Time.Seconds*2)
fmt.Println("cmd: "+time.Now().Format("20060102150405"))
})
- 2 回答
- 0 关注
- 142 浏览
添加回答
举报