APITester 기본 기능 완료
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package com.eactive.httpmockserver.client.service;
|
||||
|
||||
import com.eactive.httpmockserver.client.dto.ApiRequestDTO;
|
||||
import com.eactive.httpmockserver.client.dto.ApiResponse;
|
||||
import com.eactive.httpmockserver.client.entity.Server;
|
||||
import com.eactive.httpmockserver.client.repository.ServerRepository;
|
||||
import io.netty.bootstrap.Bootstrap;
|
||||
import io.netty.buffer.Unpooled;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.ChannelOption;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.nio.NioEventLoopGroup;
|
||||
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||
import io.netty.handler.codec.http.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Service
|
||||
public class NettyApiClient {
|
||||
|
||||
@Autowired
|
||||
ServerRepository serverRepository;
|
||||
|
||||
public CompletableFuture<ApiResponse> handleRequest(ApiRequestDTO apiRequest) throws Exception {
|
||||
|
||||
Server server = serverRepository.findById(apiRequest.getServer()).orElseThrow(() -> new Exception("Server not found"));
|
||||
String host = server.getHostname();
|
||||
int port = server.getPort();
|
||||
|
||||
CompletableFuture<ApiResponse> responseFuture = new CompletableFuture<>();
|
||||
EventLoopGroup group = new NioEventLoopGroup();
|
||||
try {
|
||||
Bootstrap b = new Bootstrap()
|
||||
.group(group)
|
||||
.channel(NioSocketChannel.class)
|
||||
.option(ChannelOption.TCP_NODELAY, true)
|
||||
.handler(new ChannelInitializer<Channel>() {
|
||||
@Override
|
||||
public void initChannel(Channel ch) {
|
||||
ch.pipeline().addLast(new HttpClientCodec());
|
||||
ch.pipeline().addLast(new HttpObjectAggregator(65536));
|
||||
ch.pipeline().addLast(new HttpContentDecompressor());
|
||||
ch.pipeline().addLast(new HttptHandler(responseFuture));
|
||||
}
|
||||
});
|
||||
|
||||
Channel ch = b.connect(host, port).sync().channel();
|
||||
|
||||
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(apiRequest.getMethod()),
|
||||
apiRequest.getPath(), Unpooled.EMPTY_BUFFER);
|
||||
|
||||
request.headers().set("Host", host);
|
||||
request.headers().set("Connection", "close");
|
||||
request.headers().set("Accept-Encoding", "gzip");
|
||||
|
||||
ch.writeAndFlush(request);
|
||||
ch.closeFuture().sync();
|
||||
} finally {
|
||||
group.shutdownGracefully();
|
||||
}
|
||||
|
||||
return responseFuture;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user