我第一次尝试通过Go例程和通道通信在Golang(1.12)中编写代码。我有Telegram机器人和一段代码,可以在发生一些更新并需要答案时与bot通信。同时,我尝试放置一些Web服务,该服务将通过http GET获取消息并将其发送给Bot。实际上,它可以工作,但是只有一次。 Bot部分仍可正常使用,但无法执行http Get请求后,它将挂起,直到超时。
我尝试将通道与缓冲区一起使用,但是在此过程中它将完全停止工作。
//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服务的通信仅发生一次。我首先想到的是由于通道阻塞,但是我将字符串发送到通道,然后读取了它,因此不应有任何阻塞。因此,我的期望是,每当我发送带有消息文本的http GET时,它将立即发送到Bot,并且系统已准备好接收下一个请求。
答案 0 :(得分:0)
似乎'msgChanel'与'msg:= <-msgChanel'仅读一次。通道被阻止,无法由HTTP请求处理程序写入。也许您应该使用for循环读取通道值。