我第一次嘗試使用 Go 例程和通道通信在 Golang (1.12) 中編寫代碼。我有 Telegram 機器人和一段代碼,可以在發(fā)生某些更新并需要答案時與機器人進行通信。同時,我嘗試放置一些 Web 服務,該服務將通過 http GET 獲取消息并將其發(fā)送給 Bot。事實上它確實有效,但只有一次。之后Bot部分仍在工作,但無法執(zhí)行http Get請求,它會一直掛起直到超時。我嘗試使用帶有緩沖區(qū)的通道,但在這種情況下它完全停止工作。//App is a structure with Bot objectstype App struct { Router *mux.Router Bot}//Initialize is method to initialize App sessionfunc (a *App) Initialize() { var err error a.Bot.BotAPI, err = telegram.NewBotAPI(TelegramBotAPIkey) checkErr(err) a.Router = mux.NewRouter() a.initializeRoutes() msgChanel = make(chan string)}func (a *App) initializeRoutes() { a.Router.HandleFunc("/", a.homePage).Methods("GET") a.Router.Path("/message/send").Queries("msg", "{msg}").HandlerFunc(a.getMessage).Methods("GET")}}// Handling of requests to send/messagefunc (a *App) getMessage(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "-----Send message to Bot-------") vars := mux.Vars(r) if vars["msg"] != "" { fmt.Fprintln(w, vars["msg"]) msgChanel <- vars["msg"] }// Run is all about running applicationfunc (a *App) Run() { var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() msg := <-msgChanel a.Bot.generateAnswer(msgid, msg) }() go func() { var msg string defer wg.Done() a.Bot.BotAPI.Debug = true u := telegram.NewUpdate(0) u.Timeout = 60 updates, err := a.Bot.BotAPI.GetUpdatesChan(u) checkErr(err) for update := range updates { if update.Message == nil { continue } msg = "" msgid = update.Message.Chat.ID a.Bot.generateAnswer(msgid, msg) } }() log.Fatal(http.ListenAndServe(":8080", a.Router)) wg.Wait()}我的問題是沒有錯誤消息。我運行應用程序,然后它在 Bot 通信方面工作,但與 Web 服務的通信僅發(fā)生一次。我的第一個想法是,這是因為通道阻塞,但是我將字符串發(fā)送到通道,然后我讀取它,所以它不應該有任何阻塞。所以我的期望是,每次當我發(fā)送帶有消息文本的 http GET 時,它將立即發(fā)送到 Bot,并且系統(tǒng)已準備好接收下一個請求。
1 回答

至尊寶的傳說
TA貢獻1789條經(jīng)驗 獲得超10個贊
似乎“msgChanel”只用“msg := <-msgChanel”讀取一次。通道被阻塞并且無法由 HTTP 請求處理程序寫入。也許您應該使用 for 循環(huán)讀取通道值。
- 1 回答
- 0 關注
- 130 瀏覽
添加回答
舉報
0/150
提交
取消