@@ -10,20 +10,31 @@ use lazy_static::lazy_static;
10
10
use reqwest:: StatusCode ;
11
11
use serde:: Deserialize ;
12
12
use serde_json:: json;
13
- use std:: net:: { Ipv4Addr , SocketAddrV4 , TcpListener } ;
13
+ use std:: {
14
+ io:: { Error , ErrorKind } ,
15
+ net:: { Ipv4Addr , SocketAddrV4 , TcpListener } ,
16
+ sync:: Arc ,
17
+ } ;
18
+
19
+ pub struct PortManager {
20
+ pub tcp_listener : Arc < TcpListener > ,
21
+ }
14
22
15
- pub fn random_free_port ( ) -> u16 {
16
- let addr = SocketAddrV4 :: new ( Ipv4Addr :: UNSPECIFIED , 0 ) ;
17
- TcpListener :: bind ( addr )
18
- . unwrap ( )
19
- . local_addr ( )
20
- . unwrap ( )
21
- . port ( )
23
+ impl PortManager {
24
+ pub fn new ( ) -> Self {
25
+ let addr = SocketAddrV4 :: new ( Ipv4Addr :: UNSPECIFIED , 0 ) ;
26
+ Self {
27
+ tcp_listener : Arc :: new ( TcpListener :: bind ( addr ) . unwrap ( ) ) ,
28
+ }
29
+ }
22
30
}
23
31
24
32
lazy_static ! {
25
- #[ derive( Debug ) ]
26
- pub static ref SERVER_PORT : u16 = random_free_port( ) ;
33
+ pub static ref PORT_MAN : Arc <PortManager > = Arc :: new( PortManager :: new( ) ) ;
34
+ }
35
+
36
+ pub fn get_instance_port ( ) -> u16 {
37
+ PORT_MAN . tcp_listener . local_addr ( ) . unwrap ( ) . port ( )
27
38
}
28
39
29
40
#[ derive( Debug , Deserialize ) ]
@@ -102,15 +113,23 @@ async fn response(req_body: String) -> impl Responder {
102
113
}
103
114
104
115
pub async fn spawn_server ( ) -> std:: io:: Result < ( ) > {
105
- let port = SERVER_PORT . to_owned ( ) ;
116
+ let port = get_instance_port ( ) ;
117
+
118
+ let tcp_listener = PORT_MAN
119
+ . tcp_listener
120
+ . try_clone ( )
121
+ . map_err ( |e| Error :: new ( ErrorKind :: AddrNotAvailable , e. to_string ( ) ) ) ?;
122
+
106
123
eprintln ! ( "Server is running at {:?}" , port) ;
107
124
HttpServer :: new ( || {
108
125
App :: new ( )
109
126
. service ( config)
110
127
. service ( command)
111
128
. service ( response)
112
129
} )
113
- . bind ( ( "127.0.0.1" , port ) ) ?
130
+ . listen ( tcp_listener ) ?
114
131
. run ( )
115
- . await
132
+ . await ?;
133
+
134
+ Ok ( ( ) )
116
135
}
0 commit comments