doutan1905 2016-11-03 08:45
浏览 189
已采纳

异步请求多个响应golang

I need to make a request to a server that return different responses at different times. I mean, the server generate different responses and these responses take different execution time, so server return the responses as soon as they are available.

And I want print in the screen (by the moment, I'd settle with that) these responses as soon as the server returns me.

All what I could do until now is print the responses but only when the server returns all the responses. So if the first response take 1sec, and the last response take 10sec, my code needs to wait 10sec to print all the messages.

EDIT: to add code I have:

//Config is gotten from yml file
RestConfig       = Config["rest"].(map[string]interface{})
ServerConfig     = Config["server"].(map[string]interface{})
RequestUrl      := ServerConfig["url"]

RequestReader   := bytes.NewReader(body)
Request, _      := http.NewRequest("POST", RequestUrl.(string), RequestReader)

//AppendHeaders append the needing headers to the request 
client.AppendHeaders(Request, RestConfig["headers"])

//the type of client.HttpClient is *http.Client
Response, _     := client.HttpClient.Do(Request)

//And to print in the screen
defer Response.Body.Close()

fmt.Println( "-> Receiving response:
---
" )
fmt.Println( Response , "
---
-> Response body:
---
")
body_resp, _ := ioutil.ReadAll(Response.Body)
fmt.Println( string(body_resp) )
fmt.Println( "
--
")

Any way to do it??

Thank you very much.

  • 写回答

2条回答 默认 最新

  • dpfz27768 2016-11-09 11:01
    关注

    Finally my code , is like this:

    package main
    
    import (
        "fmt"
        "log"
        "bytes"
        "strings"
        "bufio"
        "net/http"
    )
    
    func main() {
      var body = "The body"
      RequestReader := bytes.NewReader([]byte(body))
      req, err := http.NewRequest("POST", "the_url", RequestReader)
      if err != nil {
        log.Fatal(err)
      }
      req.Header.Add("Accept", "application/xml")
      req.Header.Add("Content-Type", "application/xml")
      req.Header.Add("AG-Authorization", "key")
      req.Header.Add("AG-Forwarded-Hosts", "*")
    
      resp, err := (&http.Client{}).Do(req)
      if err != nil {
        log.Fatal(err)
      }
      reader := bufio.NewReader(resp.Body)
      message := ""
      for {
        line, err := reader.ReadBytes('
    ')
        if err != nil {
          log.Fatal(err)
     }
        message = message + string(line)
        if strings.Contains(message, "<!-- End mark for each message -->"){
            fmt.Println(message)
            message = ""
        }
      }
    }
    

    Thank everyone.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值