ヘッダを付けたい時はRequestオブジェクトを一旦作ります。
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func main() {
data := map[string]interface{}{
"username": "test@example.com",
"password": "password123456",
}
// byte配列にする
b, err := json.Marshal(data)
if err != nil {
fmt.Printf("failed to encode json")
return
}
url := "https://api-jp.kii.com/api/oauth2/token"
// byte配列のReaderにする
r := bytes.NewReader(b)
req, err := http.NewRequest("POST", url, r)
if err != nil {
fmt.Printf("failed to create request")
return
}
// ヘッダを付ける
req.Header.Add("content-type", "application/json")
req.Header.Add("x-kii-appid", "<your App Id>")
req.Header.Add("x-kii-appkey", "<your App Key>")
// クライアントオブジェクトを作って
client := &http.Client{}
// それ経由でリクエストを投げる
resp, err2 := client.Do(req)
if err2 != nil {
fmt.Printf("failed to execute")
return
}
// 結果をJSON Objectにする
doc := json.NewDecoder(resp.Body)
var obj map[string]interface{}
doc.Decode(&obj)
// で、idをとりだしてみる
v := obj["id"]
if id, ok := v.(string); ok {
fmt.Printf("id=\n%s\nStatus=%d", id, resp.StatusCode)
}
}
重要そうな部分だけ取り出して説明してみます。
req, err := http.NewRequest("POST", url, r)
Requestオブジェクトを作ります。この時点でPOSTに渡すデータをセットするのは初めて見たかもです。
req.Header.Add("content-type", "application/json")
リクエストにHTTPヘッダを追加します。まぁ、こんな風に書くよねーといったところでしょうか。
client := &http.Client{}
// それ経由でリクエストを投げる
resp, err2 := client.Do(req)
「投げる人」は別途必要なので、言われた通りにClientオブジェクトを作ってリクエストを投げてもらいます。