目前我正在开发一个可能需要几秒到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"))
}
Run Code Online (Sandbox Code Playgroud)
您的频道未初始化,并且根据规范,永久发送nil频道块.这是因为http.ListenAndServe是一个阻塞操作,所以既没有requestChannel = make(chan Request)也没有go func()被调用.
移动http.ListenAndServe到main块的末尾应该可以解决问题.