英文:
Golang: Simultaneous function Calls for http post request
问题
我需要同时调用多个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)
}
}
感谢帮助,我需要在运行程序时获得相同的时间(以毫秒为单位)。
英文:
I need to call multiple URL at the same time. My functions get called at the same time (in milli seconds) but the moment I add a Http post request to the code it gets called one after the other. Below is the code:
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)
}
}
Appreciate help, I need to get the same time (in milliseconds) when I run the program.
答案1
得分: 3
这是通过使用Goroutines实现的。
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)
}
}
英文:
This is achieved by using Goroutines
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论