LoginSignup
3
3

More than 5 years have passed since last update.

goでchatworkにメッセージを送信する

Posted at

http://developer.chatwork.com/ja/endpoint_rooms.html#POST-rooms-room_id-messages
に書いてあるとおりの事を実行するだけです。

ヘッダーに"Content-Type", "application/x-www-form-urlencoded"
を入れないと、bodyが認識されませんでしたので注意です。

package main

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

func main() {
    apiUrl := "https://api.chatwork.com/"
    resource := "/v1/rooms/(ルーム番号)/messages"

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := fmt.Sprintf("%v", u) 

    data := url.Values{}
    data.Set("body", "test")
    fmt.Println(data.Encode())

    client := &http.Client{}
    r, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode()))
    r.Header.Add("X-ChatWorkToken", "APIトークン")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    resp, _ := client.Do(r)

    defer resp.Body.Close()
    contents, _ := ioutil.ReadAll(resp.Body)

    fmt.Println(resp.Status)
    fmt.Printf("result: %s\n", contents)
    fmt.Println(urlStr)
}
3
3
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
3
3