server: enable custom listener API

This commit is contained in:
Will Owens 2025-10-25 05:05:45 -05:00
parent 42d8a51a93
commit 1dacb4f91b
No known key found for this signature in database
GPG key ID: 8C8384B16B623DA6
2 changed files with 17 additions and 3 deletions

View file

@ -2,11 +2,14 @@ package server
import (
"context"
"net"
)
// RunOptions holds a set of configurations for Server.Run().
type RunOptions struct {
gracefullCtx context.Context
listener net.Listener
}
// RunOption is an option of Server.Run().
@ -19,3 +22,10 @@ func WithGracefullContext(ctx context.Context) RunOption {
options.gracefullCtx = ctx
}
}
// WithListener allows the caller to override the default listener
func WithListener(l net.Listener) RunOption {
return func(options *RunOptions) {
options.listener = l
}
}

View file

@ -117,9 +117,13 @@ func (server *Server) Run(ctx context.Context, options ...RunOption) error {
log.Printf("Port number configured to `0`, choosing a random port")
}
hostPort := net.JoinHostPort(server.options.Address, server.options.Port)
listener, err := net.Listen("tcp", hostPort)
if err != nil {
return errors.Wrapf(err, "failed to listen at `%s`", hostPort)
listener := opts.listener
if listener == nil {
listener, err = net.Listen("tcp", hostPort)
if err != nil {
return errors.Wrapf(err, "failed to listen at `%s`", hostPort)
}
}
scheme := "http"