Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions examples/webhook/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"crypto/subtle"
"encoding/json"
"fmt"
"io"
Expand All @@ -17,12 +18,17 @@
// Minimal webhook receiver: starts HTTP server, parses updates from YM and replies via SendToChat.
// Env:
// YM_TOKEN (required), YM_REPLY_CHAT (optional default from incoming update),
// YM_WEBHOOK_SECRET (required, value expected in X-Webhook-Secret header),
// YM_PORT (default 8080).
func main() {
token := os.Getenv("YM_TOKEN")
if token == "" {
log.Fatal("YM_TOKEN is required")
}
webhookSecret := os.Getenv("YM_WEBHOOK_SECRET")
if webhookSecret == "" {
log.Fatal("YM_WEBHOOK_SECRET is required")
}
port := os.Getenv("YM_PORT")
if port == "" {
port = "8080"
Expand All @@ -35,10 +41,22 @@

http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
body, _ := io.ReadAll(r.Body)
if subtle.ConstantTimeCompare([]byte(r.Header.Get("X-Webhook-Secret")), []byte(webhookSecret)) != 1 {
http.Error(w, "unauthorized", http.StatusUnauthorized)

return
}

r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "bad request", http.StatusBadRequest)

return
}

var upd ym.Update
if err := json.Unmarshal(body, &upd); err != nil {

Check failure on line 59 in examples/webhook/main.go

View workflow job for this annotation

GitHub Actions / Lint

shadow: declaration of "err" shadows declaration at line 51 (govet)
http.Error(w, "bad request", http.StatusBadRequest)

return
Expand All @@ -52,7 +70,7 @@
target = ym.ChatID(replyChat)
}

_, err := s.Messages.SendToChat(r.Context(), target, "echo: "+upd.Text, &messages.SendMessageOptions{

Check failure on line 73 in examples/webhook/main.go

View workflow job for this annotation

GitHub Actions / Lint

shadow: declaration of "err" shadows declaration at line 51 (govet)
ReplyToMessageID: fmt.Sprintf("%d", upd.MessageID),
})
if err != nil {
Expand All @@ -61,7 +79,7 @@
}

w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte(`{"ok":true}`))
_, err = w.Write([]byte(`{"ok":true}`))
if err != nil {
log.Printf("write failed: %v", err)

Expand Down
Loading