From f039fd8203c03a8fbcfeb8d3d357eb612a3d08d8 Mon Sep 17 00:00:00 2001 From: Hugo Landau Date: Fri, 12 Dec 2014 12:17:39 +0000 Subject: [PATCH] Add NotifyStartedFunc field to Server Adds a field, NotifyStartedFunc func() to Server. If non-nil, it is called after a server starts listening. This is useful for synchronization purposes, for example when a daemon needs to drop privileges after binding. Otherwise, there is no way to determine when the server has begun listening and hardcoded delays (!) must be used or race conditions may occur. --- server.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/server.go b/server.go index ef46c5cd..51916be6 100644 --- a/server.go +++ b/server.go @@ -223,6 +223,9 @@ type Server struct { // Unsafe instructs the server to disregard any sanity checks and directly hand the message to // the handler. It will specfically not check if the query has the QR bit not set. Unsafe bool + // If set, called once the server has started listening. This is useful if + // you need to drop privileges only after binding. + NotifyStartedFunc func() // For graceful shutdown. stopUDP chan bool @@ -370,6 +373,11 @@ func (srv *Server) getReadTimeout() time.Duration { // Each request is handled in a seperate goroutine. func (srv *Server) serveTCP(l *net.TCPListener) error { defer l.Close() + + if srv.NotifyStartedFunc != nil { + srv.NotifyStartedFunc() + } + handler := srv.Handler if handler == nil { handler = DefaultServeMux @@ -401,6 +409,10 @@ func (srv *Server) serveTCP(l *net.TCPListener) error { func (srv *Server) serveUDP(l *net.UDPConn) error { defer l.Close() + if srv.NotifyStartedFunc != nil { + srv.NotifyStartedFunc() + } + handler := srv.Handler if handler == nil { handler = DefaultServeMux