いきなり結論のコード
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型にキャストしています。
さいごに
最後まで読んで頂いてありがとうございます。
とてもシンプルなコードですが、接続の確認の際によく使いそうなので、共有させて頂きました。