Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"fmt"
"math/rand"
"os/exec"
"time"
)
type response interface {}
// go:generate stringer -type=requestCommand
type requestCommand int
const(
genNum requestCommand = iota
runCmd
)
type request struct {
cmd requestCommand
data interface {}
out chan response
}
func processRequest(req request) {
switch req.cmd {
case genNum:
req.out <- rand.Intn(100)
case runCmd:
go func() {
time.Sleep(1*time.Second)
cmd := req.data.(string)
out, err := exec.Command(cmd).Output()
if err != nil {
req.out <- err.Error()
} else {
req.out <- string(out)
}
}()
}
}
func eventLoop(done chan struct{}, inCh chan request) {
for {
select {
case req := <-inCh:
processRequest(req)
case <-done:
break
}
}
}
func main() {
done := make(chan struct{})
defer close(done)
inCh := make(chan request, 10)
defer close(inCh)
go eventLoop(done, inCh)
resp1 := make(chan response, 1)
inCh <- request{
resp1,
runCmd,
"ls",
}
resp2 := make(chan response, 1)
inCh <- request{
resp2,
genNum,
"resp1",
}
fmt.Println(<-resp2)
fmt.Println(<-resp1)
done <- struct{}{}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.