用Go语言发送HTTP GET请求

2021-06-18  本文已影响0人  louyang

参照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/

上一篇下一篇

猜你喜欢

热点阅读