From 36c5472987a50572b2a0e44757fe5ceb62149ccd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=D0=B0ramtamt=D0=B0m?= <7326800+tarampampam@users.noreply.github.com> Date: Fri, 21 Apr 2023 16:33:33 +0400 Subject: [PATCH] feat: IPv6 support (#192) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🐛 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 --- CHANGELOG.md | 8 ++++++++ internal/cli/shared/flags.go | 2 +- internal/http/server.go | 25 ++++++++++++++++++++++--- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bbd6f9..4a0a770 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/internal/cli/shared/flags.go b/internal/cli/shared/flags.go index 06a04d8..6f7be21 100644 --- a/internal/cli/shared/flags.go +++ b/internal/cli/shared/flags.go @@ -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()}, } diff --git a/internal/http/server.go b/internal/http/server.go index 4863062..7ba0c52 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -1,7 +1,10 @@ package http import ( - "strconv" + "errors" + "fmt" + "net" + "strings" "time" "github.com/fasthttp/router" @@ -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 {