@@ -3,17 +3,61 @@ package lib
33import (
44 "fmt"
55 "net/http"
6+ "strconv"
7+ "strings"
68 "os"
79 "os/exec"
10+ "github.com/phayes/freeport"
11+ "regexp"
812)
913
1014var args = os .Args [1 :]
15+ var port = - 1
16+ var portSwitch = false
17+ var cmd * exec.Cmd
1118
1219func ExecuteArgs () int {
13- var cmd * exec.Cmd
20+ freeport , err := freeport .GetFreePort ()
21+ if err != nil {
22+ fmt .Printf ("Failed to get port" )
23+ }
24+
1425 if len (args ) > 1 {
1526 program := args [0 ]
1627 argv := args [1 :]
28+
29+ if portSwitch {
30+ port = freeport
31+ replaced := false
32+ // find numbers in arguments and replace with free port
33+ for i , s := range argv {
34+ if _ , errA := strconv .Atoi (s ); errA == nil {
35+ fmt .Printf ("Changing port %q to %q for new container instance.\n " , s , strconv .Itoa (port ))
36+ argv [i ] = strconv .Itoa (port )
37+ }
38+ }
39+
40+ // attempt to replace in structures like --port=4433
41+ if replaced == false {
42+ for j , t := range argv {
43+ regex := regexp .MustCompile ("[0-9]+" )
44+ found := regex .FindAllString (t , - 1 )
45+ // ensure argument only has one number and ends with this number
46+ if len (found ) == 1 && strings .HasSuffix (t , found [0 ]) && strings .Contains (t , "=" ) {
47+ fmt .Printf ("Changing port %q of parameter %q to %q for new container instance.\n " , found [0 ], t , strconv .Itoa (port ))
48+ argv [j ] = strings .Replace (argv [j ], found [0 ], strconv .Itoa (port ), - 1 )
49+ }
50+ }
51+ }
52+
53+ } else {
54+ // try to set port according to arguments
55+ for _ , s := range argv {
56+ if val , errA := strconv .Atoi (s ); errA == nil {
57+ port = val
58+ }
59+ }
60+ }
1761
1862 cmd = exec .Command (program , argv ... )
1963 } else if len (args ) > 0 {
@@ -28,7 +72,7 @@ func ExecuteArgs() int {
2872 cmd .Stdout = os .Stdout
2973 cmd .Stderr = os .Stderr
3074 // keep stdin open
31- _ , err : = cmd .StdinPipe ()
75+ _ , err = cmd .StdinPipe ()
3276
3377 err = cmd .Run ()
3478
@@ -44,3 +88,22 @@ func Shutdown(w http.ResponseWriter, req *http.Request) {
4488
4589 go os .Exit (0 )
4690}
91+
92+ func Portrequest (w http.ResponseWriter , req * http.Request ) {
93+ concatenated := strings .Join ([]string {"Use:" ,strconv .Itoa (port ), "-Port" }, "" )
94+ fmt .Fprintf (w , concatenated )
95+ fmt .Println ("Reported port" )
96+ }
97+
98+ func EnablePortSwitch (w http.ResponseWriter , req * http.Request ) {
99+ portSwitch = true
100+ cmd .Process .Kill ()
101+ fmt .Fprintf (w , "Port switching enabled, restarted server" )
102+ fmt .Println ("Enabled port switching, restarted server" )
103+ }
104+
105+ func KillServer (w http.ResponseWriter , req * http.Request ) {
106+ cmd .Process .Kill ()
107+ fmt .Fprintf (w , "The server is dead, long live the server" )
108+ fmt .Println ("Killed server as requested" )
109+ }
0 commit comments