Created
February 16, 2019 09:19
-
-
Save astavonin/d5fca2be38ca1c7da7682cdb3c07b4cb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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