Skip to content

Commit

Permalink
QueryContext() for context cancellation support (#117)
Browse files Browse the repository at this point in the history
* QueryContext() for context cancellation support
  • Loading branch information
jcodybaker authored Mar 21, 2024
1 parent 73e338a commit 9f136d7
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package mdns

import (
"context"
"fmt"
"log"
"net"
Expand Down Expand Up @@ -68,13 +69,31 @@ func DefaultParams(service string) *QueryParam {
// to a channel. Sends will not block, so clients should make sure to
// either read or buffer.
func Query(params *QueryParam) error {
return QueryContext(context.Background(), params)
}

// QueryContext looks up a given service, in a domain, waiting at most
// for a timeout before finishing the query. The results are streamed
// to a channel. Sends will not block, so clients should make sure to
// either read or buffer. QueryContext will attempt to stop the query
// on cancellation.
func QueryContext(ctx context.Context, params *QueryParam) error {
// Create a new client
client, err := newClient(!params.DisableIPv4, !params.DisableIPv6)
if err != nil {
return err
}
defer client.Close()

go func() {
select {
case <-ctx.Done():
client.Close()
case <-client.closedCh:
return
}
}()

// Set the multicast interface
if params.Interface != nil {
if err := client.setInterface(params.Interface); err != nil {
Expand Down

0 comments on commit 9f136d7

Please sign in to comment.