0

When I read the nsqlookupd part of nsq source code, I found that the author used a Context truct to wrap a NSQLookupd struct and no other funcs for Context.I don't know why we use it this way, what benefits we can get by this way? The source code below here. Thank you!

context.go

type Context struct {
    nsqlookupd *NSQLookupd
}

nsqlookupd.go

func (l *NSQLookupd) Main() {
ctx := &Context{l}

tcpListener, err := net.Listen("tcp", l.opts.TCPAddress)
if err != nil {
    l.logf(LOG_FATAL, "listen (%s) failed - %s", l.opts.TCPAddress, err)
    os.Exit(1)
}
l.Lock()
l.tcpListener = tcpListener
l.Unlock()
tcpServer := &tcpServer{ctx: ctx}
l.waitGroup.Wrap(func() {
    protocol.TCPServer(tcpListener, tcpServer, l.opts.Logger)
})

1 Answers1

0

Because future-proofing.

Context struct provides a way to wrap context-specific data into a single structure. At this point the context contains a only a pointer to an NSQLookupd struct. However, in case Context would need to be extended somehow then all you'd have to do would be to just add more fields to the struct. You could implement struct methods as well.

All this would require no changes to the internal APIs in the program, since all those new fields and methods are wrapped into the struct and that is already being passed around in the program. You would most likely have to change the way that struct is initialized.

vtorhonen
  • 2,297
  • 14
  • 19