Webhook URLを設定し、イベントを受信する方法を確認します。
ドキュメントに従い準備(リンク)
mkdir line-messaging-api-go
cd line-messaging-api-go
go mod init line-messaging-api-gopackage main
import (
"encoding/json"
"io"
"log"
"net/http"
)
const (
port = "8080"
)
func main() {
http.HandleFunc("/webhook", webhookHandler)
log.Printf("server started: http://localhost:$s", port)
log.Printf("webhook endpoint: http://localhost:$s/webhook", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusOK)
w.Write([]byte("LINE webhook endpoint is running."))
return
}
rawBody, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read body", http.StatusBadRequest)
return
}
defer r.Body.Close()
var decodedBody any
_ = json.Unmarshal(rawBody, &decodedBody)
log.Printf(
"signature=%s body=%s decoded=%v",
r.Header.Get("X-Line-Signature"),
string(rawBody),
decodedBody,
)
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
Cloud RunにGithub経由でデプロイし、発行されたURLを「Messaging API設定>Webhook URL>編集」で設定します。
Cloud Run上のログで、イベント受信を確認できました。
©Omori
MEOW!