[Go] POST リクエストを送信する
作成日: 2020年09月07日
Go で POST リクエストを送信するサンプルコードです。リクエストボディは JSON 形式で送信しています。
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type RequestBody struct {
Something string
}
func main() {
requestBody := &RequestBody{
Something: "Hello",
}
jsonString, err := json.Marshal(requestBody)
if err != nil {
panic("Error")
}
endpoint := "https://documentroot.org"
req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(jsonString))
if err != nil {
panic("Error")
}
req.Header.Set("Content-Type", "application/json")
client := new(http.Client)
resp, err := client.Do(req)
if err != nil {
panic("Error")
}
defer resp.Body.Close()
byteArray, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic("Error")
}
fmt.Printf("%#v", string(byteArray))
}
説明
- リクエストボディとなる構造体
RequestBodyをjson.Marshal関数とbytes.NewBuffer関数を使って作成します。 http.NewRequest関数を使ってリクエストを作成します。- リクエストボディを JSON 形式で送信するため、
req.Header.Set("Content-Type", "application/json")で Content-Type を指定します。 http.Client.Do関数を使ってリクエストを送信します。ioutil.ReadAll関数でレスポンスボディをfmt.Printf関数で全て出力しています。