LoginSignup
281
224

More than 3 years have passed since last update.

Goでhttpリクエストを送信する方法

Last updated at Posted at 2014-08-20

Goでhttpリクエストを送る方法。
シンプルなものがあるものの、詳細まで設定しようとすると
やらなければいけないことが増えていきます。

1. シンプルなGETリクエスト

net/httpfunc Get(url string) (resp *Response, err error)
を使う。

(以下エラーは無視してます)

package main

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


func main() {
  url := "http://google.co.jp"

  resp, _ := http.Get(url)
  defer resp.Body.Close()

  byteArray, _ := ioutil.ReadAll(resp.Body)
  fmt.Println(string(byteArray)) // htmlをstringで取得
}

2. http.Clientを使ってGETリクエストを送信する。

まず、最初にhttp.Requestを初期化して、メソッド、URL、bodyの値を設定してから、http.Clientの`

func main() {
  req, _ := http.NewRequest("GET", url, nil)

  client := new(http.Client)
  resp, _ := client.Do(req)
  defer resp.Body.Close()


  byteArray, _ := ioutil.ReadAll(resp.Body)
  fmt.Println(string(byteArray))
}

これでbodyを送信できるようになりました。

3. 独自ヘッダーを追加してGETリクエストを送信する

Headerに何かつけたい場合はreqに値を設定する

  req, _ := http.NewRequest("GET", url, nil)
  req.Header.Set("Authorization", "Bearer access-token")

  client := new(http.Client)
  resp, err := client.Do(req)

リクエストヘッダー、レスポンスヘッダーの内容を取得する

リクエストヘッダー、レスポンスヘッダーの内容は
それぞれfunc DumpRequestOut func DumpResponseで確認出来る。

  req, _ := http.NewRequest("GET", url, nil)
  req.Header.Set("Authorization", "Bearer access-token")

  dump, _ := httputil.DumpRequestOut(req, true)
  fmt.Printf("%s", dump)

  client := new(http.Client)
  resp, err := client.Do(req)

  dumpResp, _ := httputil.DumpResponse(resp, true)
  fmt.Printf("%s", dumpResp)

結果

GET / HTTP/1.1
Host: google.co.jp
User-Agent: Go 1.1 package http
Authorization: Bearer access-token
Accept-Encoding: gzip

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Alternate-Protocol: 80:quic
Cache-Control: private, max-age=0
Content-Type: text/html; charset=Shift_JIS
Date: Wed, 20 Aug 2014 23:10:47 GMT
Expires: -1
...(省略)...

さらに細かい設定

cookieやらproxyの設定などは、http.Clientの持っている設定に記載していくことになる。

client := &http.Client{Transport: http.DefaultTransport}
281
224
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
281
224