Skip to content

Commit

Permalink
feat: IPv6 support (#192)
Browse files Browse the repository at this point in the history
* πŸ› fix(server.go): validate IP address before starting server
✨ feat(server.go): add support for IPv6 addresses

* ✨ feat(cli): add support for IPv6 addresses in the `--listen` flag

* πŸ› fix(server.go): add nolint comment to ignore magic number warning in ipv6 check

* πŸ› fix(server.go): use fmt.Sprintf to format IP and port instead of strconv.Itoa and string concatenation
  • Loading branch information
tarampampam committed Apr 21, 2023
1 parent 717542e commit 36c5472
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ All notable changes to this package will be documented in this file.

The format is based on [Keep a Changelog][keepachangelog] and this project adheres to [Semantic Versioning][semver].

## v2.24.0

### Added

- Support for IPv6 addresses in the `--listen` flag [#191]

[#191]:https://github.com/tarampampam/error-pages/issues/191

## v2.23.0

### Added
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/shared/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ var ConfigFileFlag = &cli.StringFlag{ //nolint:gochecknoglobals
var ListenAddrFlag = &cli.StringFlag{ //nolint:gochecknoglobals
Name: "listen",
Aliases: []string{"l"},
Usage: "IP address to Listen on",
Usage: "IP (v4 or v6) address to Listen on",
Value: "0.0.0.0",
EnvVars: []string{env.ListenAddr.String()},
}
Expand Down
25 changes: 22 additions & 3 deletions internal/http/server.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package http

import (
"strconv"
"errors"
"fmt"
"net"
"strings"
"time"

"github.com/fasthttp/router"
Expand Down Expand Up @@ -57,8 +60,24 @@ func NewServer(log *zap.Logger) Server {
}

// Start server.
func (s *Server) Start(ip string, port uint16) error {
return s.fast.ListenAndServe(ip + ":" + strconv.Itoa(int(port)))
func (s *Server) Start(ip string, port uint16) (err error) {
if net.ParseIP(ip) == nil {
return errors.New("invalid IP address")
}

var ln net.Listener

if strings.Count(ip, ":") >= 2 { //nolint:gomnd // ipv6
if ln, err = net.Listen("tcp6", fmt.Sprintf("[%s]:%d", ip, port)); err != nil {
return err
}
} else { // ipv4
if ln, err = net.Listen("tcp4", fmt.Sprintf("%s:%d", ip, port)); err != nil {
return err
}
}

return s.fast.Serve(ln)
}

type templatePicker interface {
Expand Down

0 comments on commit 36c5472

Please sign in to comment.