create api http server

This commit is contained in:
2025-07-08 20:00:25 +02:00
parent ecc9d54c3c
commit ee72f8824b
2 changed files with 76 additions and 3 deletions
@@ -1,5 +1,6 @@
package me.youhavetrouble.inviter;
import me.youhavetrouble.inviter.http.ApiServer;
import me.youhavetrouble.inviter.storage.MemoryStorage;
import me.youhavetrouble.inviter.storage.Storage;
import net.dv8tion.jda.api.JDA;
@@ -9,20 +10,65 @@ import net.dv8tion.jda.api.utils.cache.CacheFlag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Set;
public class Main {
private static final Logger LOGGER = LoggerFactory.getLogger("Inviter");
public static final Logger LOGGER = LoggerFactory.getLogger("Inviter");
private static JDA jda;
private static Storage storage;
private static ApiServer apiServer;
public static void main(String[] args) throws InterruptedException {
String token = System.getenv("DISCORD_TOKEN");
if (token == null || token.isEmpty()) {
LOGGER.error("Discord token is not set. Please set the DISCORD_TOKEN environment variable.");
System.exit(1);
}
String hostname = "127.0.0.1";
int port = 8080; // Default port
for (String arg : args) {
String[] parts = arg.split("=", 2);
if (parts.length < 2) {
LOGGER.error("Invalid argument format: {}", arg);
System.exit(1);
}
String key = parts[0];
String value = parts[1];
switch (key) {
case "hostname":
if (value.isEmpty()) {
LOGGER.error("Hostname cannot be empty.");
System.exit(1);
}
hostname = value;
break;
case "port":
try {
port = Integer.parseInt(value);
if (port <= 0 || port > 65535) {
LOGGER.error("Port must be a valid number between 1 and 65535.");
System.exit(1);
}
} catch (NumberFormatException e) {
LOGGER.error("Invalid port number: {}", value, e);
System.exit(1);
}
break;
default:
LOGGER.warn("Unknown argument: {}", key);
break;
}
}
jda = JDABuilder.create(
token,
Set.of(GatewayIntent.GUILD_INVITES)
@@ -42,8 +88,14 @@ public class Main {
storage = new MemoryStorage(jda);
LOGGER.info("Welcome to the Inviter Application!");
try {
apiServer = new ApiServer(hostname, port);
} catch (IOException e) {
LOGGER.error("Failed to start the API server on {}:{}", hostname, port, e);
System.exit(1);
}
LOGGER.info("Welcome to the Inviter Application!");
}
}
@@ -0,0 +1,21 @@
package me.youhavetrouble.inviter.http;
import com.sun.net.httpserver.HttpServer;
import me.youhavetrouble.inviter.Main;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
public class ApiServer {
private final HttpServer server;
public ApiServer(String hostname, int port) throws IllegalArgumentException, IOException {
server = HttpServer.create(new InetSocketAddress(hostname, port), 0);
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.start();
Main.LOGGER.info("Http API server started on {}:{}", hostname, port);
}
}