feat: IPv6 support (#192)

* 🐛 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
This commit is contained in:
Pаramtamtаm 2023-04-21 16:33:33 +04:00 committed by GitHub
parent 717542e045
commit 36c5472987
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 4 deletions

View File

@ -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]. 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 ## v2.23.0
### Added ### Added

View File

@ -17,7 +17,7 @@ var ConfigFileFlag = &cli.StringFlag{ //nolint:gochecknoglobals
var ListenAddrFlag = &cli.StringFlag{ //nolint:gochecknoglobals var ListenAddrFlag = &cli.StringFlag{ //nolint:gochecknoglobals
Name: "listen", Name: "listen",
Aliases: []string{"l"}, Aliases: []string{"l"},
Usage: "IP address to Listen on", Usage: "IP (v4 or v6) address to Listen on",
Value: "0.0.0.0", Value: "0.0.0.0",
EnvVars: []string{env.ListenAddr.String()}, EnvVars: []string{env.ListenAddr.String()},
} }

View File

@ -1,7 +1,10 @@
package http package http
import ( import (
"strconv" "errors"
"fmt"
"net"
"strings"
"time" "time"
"github.com/fasthttp/router" "github.com/fasthttp/router"
@ -57,8 +60,24 @@ func NewServer(log *zap.Logger) Server {
} }
// Start server. // Start server.
func (s *Server) Start(ip string, port uint16) error { func (s *Server) Start(ip string, port uint16) (err error) {
return s.fast.ListenAndServe(ip + ":" + strconv.Itoa(int(port))) 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 { type templatePicker interface {