LoginSignup
1
0

More than 3 years have passed since last update.

[Golang]HTTP接続してページ情報を取得する際、http.Get関数が一撃で簡単な件

Last updated at Posted at 2019-09-02

いきなり結論のコード

http接続のサンプル
package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    res, _ := http.Get("http://example.com") // ←これ
    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)
    fmt.Println(string(body))
}
実行結果
<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;

    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 50px;
        background-color: #fff;
        border-radius: 1em;
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        body {
            background-color: #fff;
        }
        div {
            width: auto;
            margin: 0 auto;
            border-radius: 0;
            padding: 1em;
        }
    }
    </style>    
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is established to be used for illustrative examples in documents. You may use this
    domain in examples without prior coordination or asking for permission.</p>
    <p><a href="http://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>

ちゃんと、http://example.comのページ情報が返ってきています。

解説

したこと

  • 今回はhttp://example.com/に接続し、取得したページ情報をbodyという変数に格納しています。
  • コードの最後では、このbodyを出力して、内容の確認としております。

res.Body.Close()でクローズ

defer res.Body.Close()
  • 接続をクローズしています。
  • deferを使うことで、ここに書き込んでいますが、実行されるのはmain関数の一番最後になります。可読性も高いですし。便利です。

ioutil.ReadAll(res.Body)で読み込む

body, _ := ioutil.ReadAll(res.Body)
  • resには取得したページデータが入っています。
  • res.Bodyとすることで、ページデータの本体を指定しています。
  • ioutil.ReadAll()で、上記のものを読み込みます。この読み込みの際、byte型で読み込むので、後の処理に注意が必要です。

string(body)でString型にキャストして出力

fmt.Println(string(body))

先述の通り、ioutil.ReadAll()では、byte型で読み込むので、今回は念のために、出力のタイミングでstring型にキャストしています。

さいごに

最後まで読んで頂いてありがとうございます。
とてもシンプルなコードですが、接続の確認の際によく使いそうなので、共有させて頂きました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0