16
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GoでhttpリクエストにHostを設定するにはreq.Headerではなくreq.Hostを使う

Posted at

ちょっとハマったのでメモです。
GoでhttpリクエストにHostを設定するには http.RequestHost フィールドを設定します。

コード例はこんな感じです。

    u := "http://127.0.0.1"
    req, err := http.NewRequest("GET", u, nil)
    if err != nil {
        return err
    }

    req.Host = "example.com"

    resp, err := client.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

req.Host = "example.com" のところを req.Header.Set("Host", "example.com") とか req.Header.Add("Host", "example.com") と書くと Host ヘッダーが設定されなくてハマりました。

Issue 7682 - go - net/http: Setting custom "Host" request header doesn't have effect - The Go Programming Language - Google Project Hostingというイシューがあって正しい書き方にたどりつけました。

16
10
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
16
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?