gpt4 book ai didi

Goroutines 通信槽 channel 只工作一次

转载 作者:数据小太阳 更新时间:2023-10-29 03:18:52 31 4
gpt4 key购买 nike

我第一次尝试使用 go-routine 和 channel 通信在 Golang (1.12) 中编写代码。我有 Telegram 机器人和一段代码,可以在发生某些更新和需要回答时与机器人通信。同时,我尝试放置一些 Web 服务,该服务将通过 http GET 获取消息并将其发送给 Bot。事实上它有效,但只有一次。之后Bot部分还在工作,但是http Get请求无法执行,一直挂到超时。

我尝试将 channel 与缓冲区一起使用,但在此它完全停止工作。


//App is a structure with Bot objects
type App struct {
Router *mux.Router
Bot
}

//Initialize is method to initialize App session
func (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/message
func (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 application
func (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 服务的通信只发生了一次。我的第一个想法是这是因为 channel 阻塞,但我将字符串发送到 channel ,然后我读取它,所以它不应该有任何阻塞。所以我的期望是,每次我发送带有消息文本的 http GET 时,它都会立即发送给 Bot,并且系统已准备好接收下一个请求。

最佳答案

'msgChanel' 似乎只读了一次'msg := <-msgChanel'。 channel 被阻塞,无法由 HTTP 请求处理程序写入。也许您应该使用 for 循环读取 channel 值。

关于Goroutines 通信槽 channel 只工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57040318/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com