I'm trying to use a goroutine to write item to database. The goroutine however doesn't seem to do anything for some reason.
I've got following functions:
func addEvent(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
fmt.Println(string(body[:]))
if err != nil {
panic(err)
}
eventCh := make(chan []byte)
eventCh <- body
go models.WriteEventToDb(eventCh)
}
and
func WriteEventToDb(eventCh chan []byte) {
fmt.Println("event")
event := <-eventCh
newEvent := createNewEvent(event)
err := db.Insert(&newEvent)
if err != nil {
panic(err)
}
}
Any idea why WriteEventToDb does not run?
Your function blocks before it gets to start the goroutine:
eventCh := make(chan []byte)
eventCh <- body
This makes a new channel, and before it can be passed off to any other routine, it tries to send a message to that channel. Since the channel is unbuffered and nothing is reading from it, the send blocks indefinitely.