LoginSignup
12
11

More than 5 years have passed since last update.

LINE NotifyをGoで送る #golang #linedevday

Posted at

コマンドラインで色々試しやすいようにシェルスクリプトっぽくしてます

notify.go
//usr/bin/env go run $0 $@ ; exit

package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "net/url"
    "strings"
)

func main() {
    token := flag.String("token", "", "LINE notify token")
    flag.Parse()

    text := flag.Arg(0)

    if *token == "" {
        log.Fatal("not token")
    }

    if text == "" {
        log.Fatal("not text")
    }

    data := url.Values{"message": {text}}
    r, _ := http.NewRequest("POST", "https://notify-api.line.me/api/notify", strings.NewReader(data.Encode()))
    r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Set("Authorization", "Bearer "+*token)
    resp, err := http.DefaultClient.Do(r)
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s\n", body)
}

使い方はnotify.goとか言う名前で保存します。
$TOKENにはLINE Notifyのトークンをセットしておきます。

chmod +x notify.go
./notify.go -token $TOKEN hogehoge

もちろんbuildすることもできます。

go build -o notify notify.go
./notify -token $TOKEN hogehoge

GoでやるメリットとしてGOOSオプションでwindowsやlinux向けにもビルドできるので便利です。

12
11
1

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
12
11