Skip to content

Commit

Permalink
feat(server): add host option
Browse files Browse the repository at this point in the history
  • Loading branch information
petomalina committed Nov 22, 2021
1 parent 15f4034 commit 8030b96
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
11 changes: 11 additions & 0 deletions pkg/server/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package server

// Option is an extendable builder for server options
type Option func(s *server)

// WithHost sets the host that the server binds to
func WithHost(host string) Option {
return func(s *server) {
s.host = host
}
}
23 changes: 16 additions & 7 deletions pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,36 @@ import (
// server wraps an implementation of a HTTP server with graceful shutdown
type server struct {
ip string
host string
port string
listener net.Listener

timeout time.Duration
}

// New creates a new server instance on the given port with the given timeout
func New(port string, timeout time.Duration) (*server, error) {
func New(port string, timeout time.Duration, opts ...Option) (*server, error) {
s := &server{}
for _, opt := range opts {
opt(s)
}

addr := ":" + port
if s.host != "" {
addr = s.host + addr
}

lis, err := net.Listen("tcp", addr)
if err != nil {
return nil, fmt.Errorf("failed to create listener for the server: %w", err)
}

return &server{
ip: lis.Addr().(*net.TCPAddr).IP.String(),
port: strconv.Itoa(lis.Addr().(*net.TCPAddr).Port),
listener: lis,
s.ip = lis.Addr().(*net.TCPAddr).IP.String()
s.port = strconv.Itoa(lis.Addr().(*net.TCPAddr).Port)
s.listener = lis
s.timeout = timeout

timeout: timeout,
}, nil
return s, nil
}

// Start bootstraps a default http server and starts handling requests
Expand Down

0 comments on commit 8030b96

Please sign in to comment.