<p>People are pretty much always looking for examples of how to use channels and goroutines and the following code has a small example of that. <a href="https://github.com/joncalhoun/pipe/blob/master/cmds.go" rel="nofollow">https://github.com/joncalhoun/pipe/blob/master/cmds.go</a></p>
<p>Instead of returning an error the <code>Commands()</code> function instead returns a writer, reader, and an error channel because some of the work can't be completed until the writer returned is closed. This allows the end user to get everything with a single function call but still check for errors in the work in case any happen to occur.</p>
<p>The underlying <code>Cmds</code> type is also (at least to me) a neat example of how you can use the <a href="https://golang.org/pkg/io/#Pipe" rel="nofollow">io.Pipe()</a> function to pipe output from one place as input to another. One of the cooler functions in the <code>io</code> package that doesn't get enough attention.</p>
<hr/>**评论:**<br/><br/>epiris: <pre><p>Well done, I'm curious though why the cmds struct has a slice of WriteCloser. Wouldn't there just be one, the head of the pipe? Or are you suppose to provide each commands Stdlin separately? </p>
<p>Edit: Oh I see after reading it, its just an oversight during setup. Maybe that Cmds struct should be private since it would be difficult to use, OR move all the external setup in New and Commands directly into the cmds struct. It's not clear what purpose New serves, other than giving you a slightly more setup CMDS struct, but slightly less than Commands returns?</p></pre>joncalhoun: <pre><p>The <code>Cmds</code> struct should probably be private like you said. That was an oversight on my part.</p>
<p>Honestly, when I originally wrote this I just created the <code>Cmds</code> version that is documented in the README, but then I got curious about a version more inline with how <code>io.Pipe()</code> works and wrote the other version today. It is much shorter (code-wise) when you ignore the error channel altogether, but when you actually check for errors they end up being similar. Just another way to solve the same problem I suppose.</p>
<p>I will push an update w/ the <code>cmds</code> type being made private. Stating that so everyone doesn't think you are going crazy when I do it :)</p></pre>epiris: <pre><p>That makes sense, when those details are hidden the package will be clear and concise, thanks for taking the time to explain.</p></pre>
