Golang learns the first wave, using an HTTP GET request for the hot weather interface.
First, the content of preparation:
1, register the Gold Developer account, apply for key
2, Golang development tool Liteide (can own Baidu).
3, general understanding of the underlying grammar golang.
Second, directly on the code
Because the code comment is very detailed, it is directly on the code.
package mainimport ( "fmt" "io/ioutil" "net/http")func main() { rlt, err := doHttpGetRequest("https://restapi.amap.com/v3/weather/weatherInfo?key=你的高德key&city=110101") if err != nil { fmt.Println("net req error") } else { fmt.Println(rlt) }}// 自定义http get请求函数// 入参:请求url// 返回值:rlt,天气数据。err,错误信息// 网络请求func doHttpGetRequest(url string) (rlt string, err error) { // http.Get在net/http中,所以要import "net/http" resp, err := http.Get(url) if err != nil { return "", err } else { // 使用efer resp.Body.Close()。当doHttpGetRequest成功return之后,执行此行语句。多用于句柄关闭 defer resp.Body.Close() // io流数据读取。需要引用io/ioutil body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } else { return string(body), err } }}
Note: My German key:d2315f3b0b4e57bbf5428e755a73e692. For test use
return Result:
Test results