美文网首页
用Go语言发送HTTP GET请求

用Go语言发送HTTP GET请求

作者: louyang | 来源:发表于2021-06-18 09:26 被阅读0次

    参照https://www.jianshu.com/p/43fd85af664d启动Hello World HTTP服务器:

    $ curl localhost:6666
    Hello World!
    

    下面用go语言实现与curl命令差不多的功能:

    package main
    
    import (
        "net/http"
        "io/ioutil"
        "log"
    )
    
    func main() {
        resp, err := http.Get("http://localhost:6666")
        if err != nil {
            log.Fatal(err)
        }
    
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatal(err)
        }
    
        log.Print("Response: ", string(body))
    }
    

    运行输出:

    2021/06/17 13:11:33 Response: Hello World!
    

    参考

    https://blog.logrocket.com/making-http-requests-in-go/
    https://dev.to/kenanbek/how-to-make-http-get-request-using-golang-and-rust-10f5
    https://appdividend.com/2019/12/02/golang-http-example-get-post-http-requests-in-golang/

    相关文章

      网友评论

          本文标题:用Go语言发送HTTP GET请求

          本文链接:https://www.haomeiwen.com/subject/nagcyltx.html