gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/registry/mdns_watcher.go (about)

     1  package registry
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/micro/mdns"
     8  )
     9  
    10  type mdnsWatcher struct {
    11  	id   string
    12  	wo   WatchOptions
    13  	ch   chan *mdns.ServiceEntry
    14  	exit chan struct{}
    15  	// the mdns domain
    16  	domain string
    17  	// the registry
    18  	registry *mdnsRegistry
    19  }
    20  
    21  func (m *mdnsWatcher) Next() (*Result, error) {
    22  	for {
    23  		select {
    24  		case e := <-m.ch:
    25  			txt, err := decode(e.InfoFields)
    26  			if err != nil {
    27  				continue
    28  			}
    29  
    30  			if len(txt.Service) == 0 || len(txt.Version) == 0 {
    31  				continue
    32  			}
    33  
    34  			// Filter watch options
    35  			// wo.Service: Only keep services we care about
    36  			if len(m.wo.Service) > 0 && txt.Service != m.wo.Service {
    37  				continue
    38  			}
    39  
    40  			var action string
    41  
    42  			if e.TTL == 0 {
    43  				action = "delete"
    44  			} else {
    45  				action = "create"
    46  			}
    47  
    48  			service := &Service{
    49  				Name:      txt.Service,
    50  				Version:   txt.Version,
    51  				Endpoints: txt.Endpoints,
    52  			}
    53  
    54  			// skip anything without the domain we care about
    55  			suffix := fmt.Sprintf(".%s.%s.", service.Name, m.domain)
    56  			if !strings.HasSuffix(e.Name, suffix) {
    57  				continue
    58  			}
    59  
    60  			service.Nodes = append(service.Nodes, &Node{
    61  				Id:       strings.TrimSuffix(e.Name, suffix),
    62  				Address:  fmt.Sprintf("%s:%d", e.AddrV4.String(), e.Port),
    63  				Metadata: txt.Metadata,
    64  			})
    65  
    66  			return &Result{
    67  				Action:  action,
    68  				Service: service,
    69  			}, nil
    70  		case <-m.exit:
    71  			return nil, ErrWatcherStopped
    72  		}
    73  	}
    74  }
    75  
    76  func (m *mdnsWatcher) Stop() {
    77  	select {
    78  	case <-m.exit:
    79  		return
    80  	default:
    81  		close(m.exit)
    82  		// remove self from the registry
    83  		m.registry.mtx.Lock()
    84  		delete(m.registry.watchers, m.id)
    85  		m.registry.mtx.Unlock()
    86  	}
    87  }