Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang: web service that monitors worker goroutine

Tags:

rest

go

Suppose I'm writing a REST web service in golang. Internally I have several worker goroutine that does things. Such goroutine are triggered on demand by the HTTP API. Of course I'd like to monitor the progress of these goroutines somehow. Normally there will be a channel for the goroutine to send updates, error, etc. And the main program would do select on those channels.

However, because the even loop of the main program is busy with http.ListenAndServe(), I can't see a way to achieve this. Given that this seems like a quite common issue to have, I'm wondering if there is a design pattern that I'm missing.

[EDIT] Some more technical detail. So I have a Resource class that manages a pool of resources. Resource.DoSomething() is a long operation, so it'll kick of a goroutine in the back ground. A channel will be opened to allow status to be polled.

When a certain HTTP request comes in, this DoSomething() gets triggered. But I have no context to poll the status from. Currently my silly plan is to poll the channel for input when the next HTTP request comes in. This should be sufficient but not ideal - I'd like to know what's going on in that goroutine right away.

like image 454
lang2 Avatar asked Oct 20 '22 01:10

lang2


1 Answers

Launch a Go routine to specifically run the select that contains the monitoring, putting the select in it's own for loop:

func main() {

    go func() {
        for {
            select {
            //TODO: Insert Code Here?
            }
        }
    }()

    err := http.ListenAndServe()

    if err != nil {
        //TODO:
    }
}
like image 176
DanG Avatar answered Oct 23 '22 01:10

DanG