Skip to content

Commit

Permalink
feat: listener configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
shoriwe committed May 22, 2023
1 parent eef4081 commit c5c1bd1
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
28 changes: 28 additions & 0 deletions config/listener.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package config

import (
"crypto/tls"
"net"
)

type Listener struct {
Network string `yaml:"network"`
Address string `yaml:"address"`
TLS *TLS `yaml:"tls"`
}

func (l *Listener) Listen() (net.Listener, error) {
ls, lErr := net.Listen(l.Network, l.Address)
if lErr != nil {
return nil, lErr
}
if l.TLS == nil {
return ls, nil
}
config, cErr := l.TLS.Config()
if cErr != nil {
ls.Close()
return nil, cErr
}
return tls.NewListener(ls, config), nil
}
50 changes: 50 additions & 0 deletions config/listener_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package config

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestListener(t *testing.T) {
t.Run("No TLS", func(tt *testing.T) {
c := Listener{
Network: "tcp",
Address: "localhost:0",
}
l, lErr := c.Listen()
assert.Nil(tt, lErr)
defer l.Close()
})
t.Run("With TLS", func(tt *testing.T) {
c := Listener{
Network: "tcp",
Address: "localhost:0",
TLS: &TLS{},
}
l, lErr := c.Listen()
assert.Nil(tt, lErr)
defer l.Close()
})
t.Run("Invalid Addr", func(tt *testing.T) {
c := Listener{
Network: "tcp",
Address: "localhost:9999999",
TLS: &TLS{},
}
_, lErr := c.Listen()
assert.NotNil(tt, lErr)
})
t.Run("Invalid TLS", func(tt *testing.T) {
c := Listener{
Network: "tcp",
Address: "localhost:0",
TLS: &TLS{
CertFile: new(string),
KeyFile: new(string),
},
}
_, lErr := c.Listen()
assert.NotNil(tt, lErr)
})
}

0 comments on commit c5c1bd1

Please sign in to comment.