LoginSignup
103
82

More than 5 years have passed since last update.

Go言語 http POSTする際のContent-Type

Last updated at Posted at 2015-08-29

http pkg を使って postする際、
リクエストヘッダの違いで、若干ハマったのでメモ。

はじめに

net/http pkg の使い方に関しては、
こちらの記事が詳しいので、参考にさせていただきました。

Go net/httpパッケージの概要とHTTPクライアント実装例

コード例

■パラメータをURLエンコードする場合

要はContent-Type が、 application/x-www-form-urlencoded の場合です。

net/url pkg で定義されている type Values を使ってます。
https://golang.org/pkg/net/url/#example_Values

package hoge

import (
    "net/http"
    "net/url"
    "strings"
)

func HttpPost(url, token, device string) error {
    values := url.Values{}
    values.Set("token", token)
    values.Add("device", device)

    req, err := http.NewRequest(
        "POST",
        url,
        strings.NewReader(values.Encode()),
    )
    if err != nil {
        return err
    }

    // Content-Type 設定
    req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

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

    return err
}

■パラメータがjson形式の場合

Content-Type が、 application/json の場合。
jsonStr という変数名の未加工文字列リテラルで、
json形式のパラメータを記述しています。

package hoge

import (
    "net/http"
    "net/url"
    "bytes"
)

func HttpPost(url, token, device string) error {
    jsonStr := `{"token":"` + token + `","device":"` + device + `"}`

    req, err := http.NewRequest(
        "POST",
        url,
        bytes.NewBuffer([]byte(jsonStr)),
    )
    if err != nil {
        return err
    }

    // Content-Type 設定
    req.Header.Set("Content-Type", "application/json")

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

    return err
}

参考
http://stackoverflow.com/questions/24455147/go-lang-how-send-json-string-in-post-request

103
82
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
103
82