突破具有无限循环的第三方goroutine

I'm using this to receive SNMP traps: https://github.com/soniah/gosnmp Now, lets say I want to programmatically break out of the (taken from here):

err := tl.Listen("0.0.0.0:9162")

What are my best approaches to this?

I'm somewhat new to Golang and didnt find a way to break out of a goroutine that I have no way of modifying ("3rd party").

Thanks,

Short answer: You can't. There's no way to kill a goroutine (short of killing the entire program) from outside the goroutine.

Long answer: A goroutine can listen for some sort of "terminate" signal (via channels, signals, or any other mechanism). But ultimately, the goroutine must terminate from within.

Looking at the library in your example, it appears this functionality is not provided.

Standard https://golang.org/pkg/net/#Conn interface provides special methods SetDeadline (together with SetReadDeadline and SetWriteDeadline) to set a hard connection break time for staled connections. As I see in the source code:

type GoSNMP struct {
    // Conn is net connection to use, typically established using GoSNMP.Connect()
    Conn net.Conn
     ...

    // Timeout is the timeout for the SNMP Query
    Timeout time.Duration
    ...

net.Conn interface is exported - so you may try to get direct access to it to set up a deadline.

type TrapListener struct {
    OnNewTrap func(s *SnmpPacket, u *net.UDPAddr)
    Params    *GoSNMP
    ...
}

In its turn TrapListener exports GoSNMP struct so you may have access to it. Try this:

tl := TrapListener{...}
tl.Params.Conn.SetDeadline(time.Now().Add(1*time.Second))
tl.Listen(...)

However this line disensures me - looks like it doesn't use stored connection and its options:

func (t *TrapListener) Listen(addr string) (err error) {
    ...
    conn, err := net.ListenUDP("udp", udpAddr)
    ....
}

But you may try :)