title: Kill a method in an infinite loop (golang)
body: <p>I am working with a piece of code that has an intentional infinite loop, I can't modify that code. I want to write some tests on that method (e.g. make sure it triggers actions at the right times) but I don't want to orphan a bunch of go routines. So I am trying to find a way that I can kill/interrupt that goroutine. </p>
  
  <p>I was thinking of trying to wrap it in a wrapper function that would kill it after a signal. Like this (doesn't work). </p>
  
  <pre><code>func wrap(inf func()) func() {
    return func() {
      select {
      case inf():
      case &lt;-time.After(5 * time.Second):
      }
    }
  }
  
  func main() {
    go wrap(inf())()
    // do things
  }
  </code></pre>
  
  <p>All the variations I can think of don't really work. I was thinking of wrapping the <code>inf</code> in a function that writes to a channel (that will never get called), or something with a return statement. And then the <code>select</code> can read from that. The problem is then you have to launch that. If you do it in this routine you're never getting to the <code>select</code>. If you do it in another routine, you've just made the problem worse. </p>
  
  <p>So, is there a way that I can kill that routine? </p>
  
  <p>(yes - I would rather change the infinite loop code, but can't here)</p>