Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Golang:http post请求的同时函数调用_Http_Go_Concurrency_Simultaneous - Fatal编程技术网

Golang:http post请求的同时函数调用

Golang:http post请求的同时函数调用,http,go,concurrency,simultaneous,Http,Go,Concurrency,Simultaneous,我需要同时调用多个URL。我的函数在同一时间(毫秒)被调用,但当我向代码中添加Http post请求时,它会被一个接一个地调用。代码如下: Check(url1) Check(url2) func Check(xurl string) { nowstartx := time.Now() startnanos := nowstartx.UnixNano() nowstart := startnanos / 1000000 fmt.Println(now

我需要同时调用多个URL。我的函数在同一时间(毫秒)被调用,但当我向代码中添加Http post请求时,它会被一个接一个地调用。代码如下:

Check(url1)
Check(url2)

func Check(xurl string) {

    nowstartx    := time.Now()
    startnanos   := nowstartx.UnixNano()
    nowstart := startnanos / 1000000
    fmt.Println(nowstart)

    json = {"name" : "test"}
    req, err := http.NewRequest("POST", xurl, bytes.NewBuffer(json))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{}
    resp, err := client.Do(req)

    if err != nil {
        panic(err)

    } else {
        defer resp.Body.Close()
        body, _ = ioutil.ReadAll(resp.Body)
    }

}

感谢您的帮助,我需要在运行程序时获得相同的时间(以毫秒为单位)。

这是通过使用


它们从来都不是在同一时间,你可以连续调用每一个,它们只是执行得非常快。您看过关于Go并发的任何文档了吗?例如:我经历了这个过程,它应该同时调用。我尝试了多次,但它实际上是并发调用的,除非我添加了post请求。有没有一种方法可以同时调用多个http post请求?没有,您在哪里启动了一个新的goroutine,因此您没有添加任何并发性,这两个调用无法同时执行。
go Check(url1)
go Check(url2)

func Check(xurl string) {

    nowstartx    := time.Now()
    startnanos   := nowstartx.UnixNano()
    nowstart := startnanos / 1000000
    fmt.Println(nowstart)

    json = {"name" : "test"}
    req, err := http.NewRequest("POST", xurl, bytes.NewBuffer(json))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")
    client := &http.Client{}
    resp, err := client.Do(req)

    if err != nil {
        panic(err)

    } else {
        defer resp.Body.Close()
        body, _ = ioutil.ReadAll(resp.Body)
    }

}