去循环http请求

seo*_*ppc 0 loops go

我最近开始使用GoLang,并尝试了以下方法。

package main

import (
    "fmt"
    "strings"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://uri.api.dev"

    payload := strings.NewReader("param1=example&version=2")

    req, _ := http.NewRequest("POST", url, payload)

    req.Header.Add("content-type", "application/x-www-form-urlencoded")

    for i := 1; i <= 10; i++ {

        res, _ := http.DefaultClient.Do(req)

        body, _ := ioutil.ReadAll(res.Body)

        fmt.Println(string(body))

    }

    defer res.Body.Close()

}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行此命令时,它会引发“ undefined:res”错误。我想向API uri发出10个http请求res.Body.Close(),最后使连接保持持久以提高速度。我们如何访问超出其范围的res变量并使此代码正常工作。请帮忙,谢谢

Nat*_*ate 5

Go具有块作用域,因此,如果在内部作用域中创建变量,则无法在外部作用域中访问它。循环完成后,您需要在循环外声明res才能访问它。

var res *http.Response

for i := 1; i <= 10; i++ {

    res, _ = http.DefaultClient.Do(req)

    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(string(body))

}

//This is wrong
defer res.Body.Close()
Run Code Online (Sandbox Code Playgroud)

如上所述,推迟上述res.Body.Close()也是错误的,因为您应该关闭每个读取的新主体。

同样如前所述,您绝对应该在所有通话中使用并检查err。

我可以通过一种简单而天真的方式来更改此设置:

for i := 1; i <= 10; i++ {
    url := "https://uri.api.dev"
    payload := strings.NewReader("param1=example&version=2")
    req, err := http.NewRequest("POST", url, payload)
    if err != nil {
        //Specific error handling would depend on scenario
        fmt.Printf("%v\n", err)
        return
    }
    req.Header.Add("content-type", "application/x-www-form-urlencoded")

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        //Specific error handling would depend on scenario
        fmt.Printf("%v\n", err)
        return
    }

    body, err := ioutil.ReadAll(res.Body)
        if err != nil {
        //Specific error handling would depend on scenario
        fmt.Printf("%v\n", err)
        return
    }

    fmt.Println(string(body))
    res.Body.Close()
}
Run Code Online (Sandbox Code Playgroud)

这里要考虑的事情。您要串行调用10个API。一个自然的扩展是使用'go'关键字并行或至少同时进行测试。为此,您不能在循环迭代中共享变量。就像是:

for i := 1; i <= 10; i++ {
    //Where testApi is the whole process encapsulated for one iteration
    go testApi()
}
Run Code Online (Sandbox Code Playgroud)

最后,不要过早优化。范围受限制的变量将长期防止错误和维护麻烦。

希望这可以帮助。

忍者编辑:

没有充分的理由,不要使循环从非零数字开始,这可能是思考循环的最常见方法。1-10版本感觉非常VB / VB.Net。

for i := 0; i < 10; i++ {
    //Where testApi is the whole process encapsulated for one iteration
    go testApi()
}
Run Code Online (Sandbox Code Playgroud)