Golang Getting started with programming HTTP request weather

Source: Internet
Author: User

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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.