I believe the use of channels is preferred over callbacks, is there a way to rewrite this with channels that is more idiomatic or is the use of callbacks ok here:
type SomeServer struct { }
func RunSomeServer(callback func(SomeServer)) {
someServer := SomeServer{}
// do some other setup
callback(someServer)
// tear things down
}
func TestSomeServer(t *testing.T) {
// some server only exists for the lifetime of the callback
RunSomeServer(func(someServer SomeServer) {
// run some tests against some Server
})
}
Using callbacks is very acceptable, specially for that kind of server pattern, net/*
uses it all over the place.
However, the channel version could look something like:
func RunSomeServer() <- chan *SomeServer {
ch := make(chan *SomeServer)
someServer := &SomeServer{}
go func() {
for i := 0; i < 10; i++ {
ch <- someServer //make sure someServer handles concurrent access
}
close(ch)
//tear things down
}()
return ch
}
func TestSomeServer(t *testing.T) {
ch := RunSomeServer()
for ss := range ch {
_ = ss
//do stuff with ss
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With