Skip to content

Commit

Permalink
perf: add FreePort func
Browse files Browse the repository at this point in the history
  • Loading branch information
darkjinnee committed Mar 6, 2022
1 parent eaf3236 commit f84bb1d
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 12 deletions.
44 changes: 32 additions & 12 deletions cmd/envporter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,40 @@ package main
import (
"flag"
"fmt"
"github.com/darkjinnee/envporter/pkg/porter"
"github.com/darkjinnee/envporter/internal/app/envporter"
"github.com/darkjinnee/go-err"
"os"
"strings"
)

var file *os.File
type Args struct {
File *os.File
Path string
Min int
Max int
}

var args Args

func init() {
var filePath string
flag.StringVar(
&filePath,
"f",
&args.Path,
"file",
".env",
"path to .env file",
)
flag.IntVar(
&args.Min,
"min",
3000,
"minimum port number range",
)
flag.IntVar(
&args.Max,
"max",
9999,
"maximum port number range",
)
flag.Parse()

dirPath, err := os.Getwd()
Expand All @@ -27,15 +45,15 @@ func init() {
"[Error] envporter.init: Failed to return the root path of directory",
)

if strings.EqualFold(filePath, ".env") {
filePath = strings.Join([]string{
if strings.EqualFold(args.Path, ".env") {
args.Path = strings.Join([]string{
dirPath,
filePath,
args.Path,
}, "/")
}

file, err = os.OpenFile(
filePath,
args.File, err = os.OpenFile(
args.Path,
os.O_RDWR,
os.ModePerm,
)
Expand All @@ -46,6 +64,8 @@ func init() {
}

func main() {
fmt.Print(file.Name() + "\n")
fmt.Print(porter.CheckIpv4Tcp(8081))
for min, max := range map[int]int{6000: 7000, 8000: 9999} {
fmt.Print(envporter.FreePort(min, max))
fmt.Print("\n")
}
}
32 changes: 32 additions & 0 deletions internal/app/envporter/freeport.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package envporter

import (
"github.com/darkjinnee/envporter/pkg/porter"
"math/rand"
"time"
)

var usedPorts []int

func NumberRange(min, max int) int {
rand.Seed(time.Now().UTC().UnixNano())
return min + rand.Intn(max-min)
}

func FreePort(min, max int) int {
var port int
for i := 1; i < 10; i++ {
port = NumberRange(min, max)
for _, value := range usedPorts {
if port == value || !porter.CheckIpv4Tcp(port) {
break
}
}
}

usedPorts = append(
usedPorts,
port,
)
return port
}

0 comments on commit f84bb1d

Please sign in to comment.