一个简单的示例代码,请求httpbin.org/get这个页面,返回请求的一些信息
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
url := "http://httpbin.org/get"
fmt.Printf("url: %s\n", url)
res, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", body)
}
运行结果:
url: http://httpbin.org/get
{
"args": {},
"headers": {
"Accept-Encoding": "gzip",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "Go-http-client/1.1"
},
"origin": "139.159.214.194",
"url": "http://httpbin.org/get"
}