Golang,在处理 HTTP 请求时无法将值推送到 'global' 通道
Golang, unable to have value pushed into 'global' channel when handling HTTP requests
目前我正在处理一个应用程序,它可能需要几秒钟到 1 小时以上的时间来处理。因此,在其他人正在处理时使用通道来阻止请求似乎很合适。以下是我试图完成的示例,但是我遇到了一个问题,因为在尝试将数据添加到所述通道时我的程序似乎停滞了(见下文)。
package main
import (
"net/http"
"github.com/gorilla/mux"
)
type Request struct {
Id string
}
func ConstructRequest(id string) Request {
return Request{Id: id}
}
var requestChannel chan Request // <- Create var for channel
func init() {
r := mux.NewRouter()
r.HandleFunc("/request/{id:[0-9]+}", ProcessRequest).Methods("GET")
http.Handle("/", r)
}
func main() {
// start server
http.ListenAndServe(":4000", nil)
requestChannel = make(chan Request) // <- Make channel and assign to var
go func() {
for {
request, ok := <-requestChannel
if !ok{
return
}
fmt.Println(request.Id)
}
}()
}
func ProcessRequest(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
newRequest := api.ConstructRequest(params["id"])
requestChannel <- newRequest // <- it is stopping here, not adding the value to the channel
w.Write([]byte("Received request"))
}
您的频道未初始化,并且根据规范,永远发送 nil 频道块。这是因为 http.ListenAndServe
是一个阻塞操作,所以 requestChannel = make(chan Request)
和你的 go func()
都没有被调用。
将 http.ListenAndServe
移动到 main
块的末尾应该可以解决问题。
目前我正在处理一个应用程序,它可能需要几秒钟到 1 小时以上的时间来处理。因此,在其他人正在处理时使用通道来阻止请求似乎很合适。以下是我试图完成的示例,但是我遇到了一个问题,因为在尝试将数据添加到所述通道时我的程序似乎停滞了(见下文)。
package main
import (
"net/http"
"github.com/gorilla/mux"
)
type Request struct {
Id string
}
func ConstructRequest(id string) Request {
return Request{Id: id}
}
var requestChannel chan Request // <- Create var for channel
func init() {
r := mux.NewRouter()
r.HandleFunc("/request/{id:[0-9]+}", ProcessRequest).Methods("GET")
http.Handle("/", r)
}
func main() {
// start server
http.ListenAndServe(":4000", nil)
requestChannel = make(chan Request) // <- Make channel and assign to var
go func() {
for {
request, ok := <-requestChannel
if !ok{
return
}
fmt.Println(request.Id)
}
}()
}
func ProcessRequest(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
newRequest := api.ConstructRequest(params["id"])
requestChannel <- newRequest // <- it is stopping here, not adding the value to the channel
w.Write([]byte("Received request"))
}
您的频道未初始化,并且根据规范,永远发送 nil 频道块。这是因为 http.ListenAndServe
是一个阻塞操作,所以 requestChannel = make(chan Request)
和你的 go func()
都没有被调用。
将 http.ListenAndServe
移动到 main
块的末尾应该可以解决问题。