aboutsummaryrefslogtreecommitdiff
path: root/Sources/server.swift
diff options
context:
space:
mode:
authorNavan Chauhan <navanchauhan@gmail.com>2023-12-04 23:22:34 -0700
committerNavan Chauhan <navanchauhan@gmail.com>2023-12-04 23:22:34 -0700
commit3ec3af34e4099e933bb39731036dc50bd2ce14d6 (patch)
tree94dc0ab8856a81d3f698994d38fd21647afa5bf1 /Sources/server.swift
parent6f57c8e5ad47ca3046213e11134e4f4b145e5bb8 (diff)
refactor
Diffstat (limited to 'Sources/server.swift')
-rw-r--r--Sources/server.swift88
1 files changed, 88 insertions, 0 deletions
diff --git a/Sources/server.swift b/Sources/server.swift
new file mode 100644
index 0000000..44520bb
--- /dev/null
+++ b/Sources/server.swift
@@ -0,0 +1,88 @@
+// The Swift Programming Language
+// https://docs.swift.org/swift-book
+
+import ArgumentParser
+import Foundation
+import Logging
+import NIO
+
+@main
+struct swiftGopher: ParsableCommand {
+ @Option var gopherHostName: String = "localhost"
+ @Option var port: Int = 8080
+ @Option var gopherDataDir: String = "./example-gopherdata"
+ @Option var host: String = "0.0.0.0"
+ @Flag var disableSearch: Bool = false
+ @Flag var disableGophermap: Bool = false
+
+ public mutating func run() throws {
+ let eventLoopGroup = MultiThreadedEventLoopGroup(
+ numberOfThreads: System.coreCount
+ )
+
+ defer {
+ try! eventLoopGroup.syncShutdownGracefully()
+ }
+
+ let localGopherDataDir = gopherDataDir
+ let localGopherHostName = gopherHostName
+ let localPort = port
+ let localEnableSearch = !disableSearch
+ let localDisableGophermap = disableGophermap
+
+ let logger = Logger(label: "com.navanchauhan.gopher.server")
+
+ let serverBootstrap = ServerBootstrap(
+ group: eventLoopGroup
+ )
+ .serverChannelOption(
+ ChannelOptions.backlog,
+ value: 256
+ )
+ .serverChannelOption(
+ ChannelOptions.socketOption(
+ .so_reuseaddr
+ ),
+ value: 1
+ )
+ .childChannelInitializer { channel in
+ channel.pipeline.addHandlers([
+ BackPressureHandler(),
+ GopherHandler(
+ logger: logger,
+ gopherdata_dir: localGopherDataDir,
+ gopherdata_host: localGopherHostName,
+ gopherdata_port: localPort,
+ enableSearch: localEnableSearch,
+ disableGophermap: localDisableGophermap
+ ),
+ ])
+ }
+ .childChannelOption(
+ ChannelOptions.socketOption(
+ .so_reuseaddr
+ ),
+ value: 1
+ )
+ .childChannelOption(
+ ChannelOptions.maxMessagesPerRead,
+ value: 16
+ )
+ .childChannelOption(
+ ChannelOptions.recvAllocator,
+ value: AdaptiveRecvByteBufferAllocator()
+ )
+
+ let defaultHost = host
+ let defaultPort = port
+
+ let channel = try serverBootstrap.bind(
+ host: defaultHost,
+ port: defaultPort
+ ).wait()
+
+ logger.info("Server started and listening on \(channel.localAddress!)")
+ try channel.closeFuture.wait()
+ logger.info("Server closed")
+ }
+}