Skip to content

Commit

Permalink
Added RunWithListener() to allow adaptation of other network listener…
Browse files Browse the repository at this point in the history
…s for policy services
  • Loading branch information
wneessen committed Oct 6, 2021
1 parent 499c18c commit 7a643f5
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 5 deletions.
15 changes: 10 additions & 5 deletions pps.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,18 +237,23 @@ func (s *Server) SetAddr(a string) {

// Run starts a server based on the Server object
func (s *Server) Run(ctx context.Context, h Handler) error {
sa := net.JoinHostPort(s.la, s.lp)
l, err := net.Listen("tcp", sa)
if err != nil {
return err
}
return s.RunWithListener(l, ctx, h)
}

// RunWithListener starts a server based on the Server object with a given network listener
func (s *Server) RunWithListener(l net.Listener, ctx context.Context, h Handler) error {
el := log.New(os.Stderr, "[Server] ERROR: ", log.Lmsgprefix|log.LstdFlags|log.Lshortfile)
noLog := false
ok, nlv := ctx.Value(CtxNoLog).(bool)
if ok {
noLog = nlv
}

sa := net.JoinHostPort(s.la, s.lp)
l, err := net.Listen("tcp", sa)
if err != nil {
return err
}
go func() {
<-ctx.Done()
if err := l.Close(); err != nil && !noLog {
Expand Down
47 changes: 47 additions & 0 deletions pps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,3 +284,50 @@ func TestRunDialResponses(t *testing.T) {
})
}
}

// TestRunDialWithRequestSocket starts a new server listening for connections on a UNIX socket,
// tries to connect to it and sends example data
func TestRunDialWithRequestSocket(t *testing.T) {
s := New()
sctx, scancel := context.WithCancel(context.Background())
defer scancel()
vsctx := context.WithValue(sctx, CtxNoLog, true)
us := "/tmp/pps_test_server"
l, err := net.Listen("unix", us)
if err != nil {
t.Errorf("failed to create new UNIX socket listener: %s", err)
}

h := Hi{}
go func() {
if err := s.RunWithListener(l, vsctx, h); err != nil {
t.Errorf("could not run server: %s", err)
}
}()

// Wait a brief moment for the server to start
time.Sleep(time.Millisecond * 200)

d := net.Dialer{}
cctx, ccancel := context.WithTimeout(context.Background(), time.Millisecond*500)
defer ccancel()
conn, err := d.DialContext(cctx, "unix", us)
if err != nil {
t.Errorf("failed to connect to running server: %s", err)
return
}
defer func() { _ = conn.Close() }()
rb := bufio.NewReader(conn)
_, err = conn.Write([]byte(exampleReq))
if err != nil {
t.Errorf("failed to send request to server: %s", err)
}
resp, err := rb.ReadString('\n')
if err != nil {
t.Errorf("failed to read response from server: %s", err)
}
exresp := fmt.Sprintf("action=%s\n", RespDunno)
if resp != exresp {
t.Errorf("unexpected server response => expected: %s, got: %s", exresp, resp)
}
}

0 comments on commit 7a643f5

Please sign in to comment.