go - Golang, unable to have value pushed into 'global' channel when handling HTTP requests -
currently working on application can take anywhere few seconds 1 hour + process. because of using channel block requests while others processing seems fit. following example of im trying accomplish, having issue seems program stalling when trying add data said channel (see below).
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 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 , assign var go func() { { 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 // <- stopping here, not adding value channel w.write([]byte("received request")) }
your channel not initialised and, per specification, send on nil channel blocks forever. because http.listenandserve
blocking operation, neither requestchannel = make(chan request)
nor go func()
being called.
moving http.listenandserve
end of main
block should fix problem.
Comments
Post a Comment