如何在GO中等待POST请求完成?

前端之家收集整理的这篇文章主要介绍了如何在GO中等待POST请求完成? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

嗨,我正在GO中创建一个POST请求,但是在实际完成之前终止,例如,我正在尝试拉一个docker映像,这可以通过curl通过以下操作完成:

curl -X POST https://address/images/create?fromImage=imagename 

这将返回以下内容

{"status":"Pulling from imagename","id":"latest"}
{"status":"Already exists","progressDetail":{},"id":"3d30e94188f7"}
{"status":"Already exists","id":"bf4e27765153"}
{"status":"Already exists","id":"67280fd39fba"}
.... many of those
{"status":"Pull complete","id":"21c062e2346f"}
{"status":"Digest: sha256:24f26a1344fca6d5ee1adcdsf2d01b20d7823c560ed9d2193466e36bd1f049088"}
{"status":"Pulling from imagename","id":"20161005"}
{"status":"Digest: sha256:f527dsfds88676eb25d8f7de5406f46cbc3a995345ddb4bb3d08fcf110458fe3cf"}
{"status":"Status: Downloaded newer image for imagename"}

并且图像被成功拉出

但是如果我尝试

func PullImage(imagename string,uuid string) error {
logFields := log.Fields{

    "handler": "PullImage","uuid":    uuid,}

log.WithFields(logFields).Debugf("imagename:%v",imagename)

url := fmt.Sprintf("https://%s/images/create?fromImage%s",sconf.Docker.Endpoint,imagename)
req,err := http.NewRequest("POST",url,nil)

req.Header.Set("Content-Type","application/json")
resp,err := client.Do(req)

log.WithFields(logFields).Infof("call url:%s",url)
if err != nil {
    log.WithFields(logFields).Errorf("Error in call url (%s) :%s",err)

    return errors.New(fmt.Sprintf("Error in call url (%s) :%s",err))
}


var pullresbody interface{}
err = json.NewDecoder(resp.Body).Decode(&pullresbody)
if err != nil {
    log.WithFields(logFields).Errorf("Could not unmarshal json: %s",err)
    return errors.New(fmt.Sprintf("Could not unmarshal json: %s",err))
}

    log.WithFields(logFields).Infof("response of url %s:%+v",resp)
log.WithFields(logFields).Infof("response body:%+v",pullresbody)
   return nil

}

然后我在日志中得到这个:

map[status:Pulling from imagename]

并且没有拉出图像,因此在真正完成之前停止连接该如何解决

最佳答案
解码器一次只能解码一个流中的一个对象.要获取所有对象,您需要类似

var pullRespBody interface{}
dec := json.NewDecoder(resp.Body)
var err error
for err == nil {
    err = dec.Decode(&pullRespBody)
    // Check err...
    log.WithFields(logFields).Infof("response body:%+v",pullRespBody)
    // Do something else with pullRespBody...
}
// Deal with err...
原文链接:/docker/532676.html

猜你在找的Docker相关文章