swift based web server
Repo atom2ueki/SwiftWebServer, read from GitHub 33 min ago. atom2ueki has not joined Take My Repo.
atom2ueki/SwiftWebServer is a public repo on GitHub by atom2ueki. swift based web server. It declares the MIT license on GitHub. It is written mainly in Swift, has 3 stars and last changed on 2026-08-29. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-25.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
A lightweight, Swift-based HTTP web server with middleware support.
/users/{id}) and multiple HTTP methodshost: parameter for loopback-only binds (OAuth callbacks, IPC)@MainActor-isolated: SwiftWebServer is Sendable and explicit about its run-loop contract
Add SwiftWebServer to your Package.swift:
dependencies: [
.package(url: "https://github.com/atom2ueki/SwiftWebServer.git", from: "0.3.1")
]
import SwiftWebServer
@MainActor
func startServer() -> SwiftWebServer {
let server = SwiftWebServer()
// Add middleware
server.use(LoggerMiddleware())
server.use(CORSMiddleware())
// Define routes
server.get("/hello") { req, res in
res.send("Hello, World!")
}
server.get("/users/{id}") { req, res in
let userId = req.pathParameters["id"] ?? "unknown"
res.json("""
{
"userId": "\(userId)",
"message": "User details"
}
""")
}
// Start listening. The completion fires once `status` reaches `.running`.
server.listen(8080) {
print("Server running on http://localhost:8080")
}
// Return the server so the caller can keep a reference and call
// `server.close()` later β otherwise the listener stays bound until
// process exit.
return server
}
SwiftWebServeris@MainActor-isolated. Calllisten(_:)andclose()from the main actor (which has its own run loop). All route registration and middleware/static-directory configuration must happen beforelisten(_:)β calling them on a running server traps with a clear message. Hold on to the returnedSwiftWebServerinstance for as long as you need the listener up; in app code, store it on an@MainActor-isolated owner (a model object, view-model, or app delegate property).
For flows that must not be reachable on the LAN (OAuth callbacks per
RFC 8252 Β§7.3, IPC, dev tooling), pass host: "localhost":
server.listen(8080, host: "localhost") {
print("Server running on http://localhost:8080 (loopback only)")
}
Other supported host: values: "127.0.0.1", "::1", "0.0.0.0", "::",
or any IPv4/IPv6 literal. Hostnames other than "localhost" are not
resolved β pass IP literals.
SwiftWebServer follows a middleware-based architecture where requests flow through a chain of middleware functions before reaching route handlers, and responses flow back through the same chain.
Middleware functions are the core of SwiftWebServer's extensibility. Each middleware can:
Request β [Middleware 1] β [Middleware 2] β [Route Handler]
Response β [Middleware 1] β [Middleware 2] β [Route Handler]
Middleware executes in the order it's registered using server.use(), and response processing happens in reverse order.
SwiftWebServer comes with several built-in middleware components:
Parses JSON and form data from request bodies.
server.use(BodyParser())
server.post("/api/users") { req, res in
if let jsonBody = req.jsonBody {
// Handle JSON data
let userData = jsonBody
} else if let formBody = req.formBody {
// Handle form data
let name = formBody["name"]
}
}
Logs incoming requests and outgoing responses with configurable detail levels.
// Basic logging
server.use(LoggerMiddleware())
// Detailed logging with headers
server.use(LoggerMiddleware(options: LoggerOptions(
level: .detailed,
includeHeaders: true
)))
Handles Cross-Origin Resource Sharing (CORS) headers for web applications.
// Default CORS settings
server.use(CORSMiddleware())
// Custom CORS configuration
server.use(CORSMiddleware(options: CORSOptions(
allowedOrigins: ["https://myapp.com"],
allowedMethods: [.get, .post, .put],
allowedHeaders: [.contentType, .authorization],
allowCredentials: true
)))
Parses incoming cookies and provides methods for setting response cookies.
server.use(CookieMiddleware())
// In route handlers
server.get("/login") { req, res in
// Read cookies
let sessionId = req.cookie("sessionId")
// Set cookies
res.cookie("sessionId", "abc123", attributes: CookieAttributes(
expires: Date().addingTimeInterval(3600),
httpOnly: true,
secure: true
))
}
Provides Bearer token authentication for protected routes with JWT support.
let authMiddleware = BearerTokenMiddleware(options: BearerTokenOptions(
validator: { token in
// Validate token against your auth system
return token == "valid-api-key" || validateJWT(token)
}
))
// Apply to specific routes
server.get("/protected", authMiddleware) { req, res in
// Access authenticated user info
if let authToken = req.middlewareStorage["authToken"] as? String {
res.json("""{"message": "Access granted", "token": "\(authToken)"}""")
} else {
res.json("""{"message": "Access granted"}""")
}
}
Implements conditional requests with ETag support for caching.
server.use(ETagMiddleware(options: ETagOptions(
strategy: .strong // or .weak
)))
// In route handlers
server.get("/data") { req, res in
let content = generateDynamicContent()
res.sendWithETag(content, contentType: .applicationJson)
}
The middleware system is designed to be easily extensible. You can create custom middleware by implementing the BaseMiddleware class or the ConfigurableMiddleware protocol.
import SwiftWebServer
/// Custom middleware that adds a request timestamp
class TimestampMiddleware: BaseMiddleware {
override func execute(request: Request, response: Response, next: @escaping NextFunction) throws {
// Add timestamp to request
let timestamp = Date().timeIntervalSince1970
request.middlewareStorage["timestamp"] = timestamp
// Add custom header to response
response.header("X-Request-Timestamp", "\(timestamp)")
// Continue to next middleware
try next()
// Post-processing (after route handler)
print("Request processed in \(Date().timeIntervalSince1970 - timestamp) seconds")
}
}
// Usage
server.use(TimestampMiddleware())
Middleware can share data through the request's middlewareStorage dictionary:
// In authentication middleware
class AuthMiddleware: BaseMiddleware {
override func execute(request: Request, response: Response, next: @escaping NextFunction) throws {
// Validate token and store user info
if let user = validateAndGetUser(from: request) {
request.middlewareStorage["currentUser"] = user
request.middlewareStorage["isAuthenticated"] = true
}
try next()
}
}
// In route handler
server.get("/profile") { req, res in
if let user = req.middlewareStorage["currentUser"] as? User {
res.json(user.toJSON())
} else {
res.status(.unauthorized).json(["error": "Not authenticated"])
}
}
/// Configuration options for rate limiting
public struct RateLimitOptions {
public let maxRequests: Int
public let windowSeconds: Int
public let message: String
public init(maxRequests: Int = 100, windowSeconds: Int = 60, message: String = "Rate limit exceeded") {
self.maxRequests = maxRequests
self.windowSeconds = windowSeconds
self.message = message
}
public static let `default` = RateLimitOptions()
}
/// Rate limiting middleware
public class RateLimitMiddleware: BaseMiddleware, ConfigurableMiddleware {
public typealias Options = RateLimitOptions
private let options: RateLimitOptions
private var requestCounts: [String: (count: Int, resetTime: Date)] = [:]
private let queue = DispatchQueue(label: "rateLimit", attributes: .concurrent)
public required init(options: RateLimitOptions = .default) {
self.options = options
super.init()
}
public convenience override init() {
self.init(options: .default)
}
public override func execute(request: Request, response: Response, next: @escaping NextFunction) throws {
let clientIP = request.clientIP ?? "unknown"
let now = Date()
let shouldAllow = queue.sync {
if let entry = requestCounts[clientIP] {
if now > entry.resetTime {
// Reset window
requestCounts[clientIP] = (count: 1, resetTime: now.addingTimeInterval(TimeInterval(options.windowSeconds)))
return true
} else if entry.count < options.maxRequests {
// Increment count
requestCounts[clientIP] = (count: entry.count + 1, resetTime: entry.resetTime)
return true
} else {
// Rate limit exceeded
return false
}
} else {
// First request from this IP
requestCounts[clientIP] = (count: 1, resetTime: now.addingTimeInterval(TimeInterval(options.windowSeconds)))
return true
}
}
if shouldAllow {
try next()
} else {
response.status(.tooManyRequests).send(options.message)
}
}
}
// Usage
server.use(RateLimitMiddleware(options: RateLimitOptions(
maxRequests: 50,
windowSeconds: 60,
message: "Too many requests. Please try again later."
)))
SwiftWebServer supports flexible routing with path parameters and multiple HTTP methods.
// HTTP Methods
server.get("/users") { req, res in res.send("Get all users") }
server.post("/users") { req, res in res.send("Create user") }
server.put("/users/{id}") { req, res in res.send("Update user") }
server.delete("/users/{id}") { req, res in res.send("Delete user") }
// Single parameter
server.get("/users/{id}") { req, res in
let userId = req.pathParameters["id"] ?? "unknown"
res.send("User ID: \(userId)")
}
// Multiple parameters
server.get("/users/{userId}/posts/{postId}") { req, res in
let userId = req.pathParameters["userId"] ?? "unknown"
let postId = req.pathParameters["postId"] ?? "unknown"
res.json("""
{
"userId": "\(userId)",
"postId": "\(postId)"
}
""")
}
server.get("/search") { req, res in
let query = req.queryParameters["q"] ?? ""
let page = Int(req.queryParameters["page"] ?? "1") ?? 1
res.json("""
{
"query": "\(query)",
"page": \(page),
"results": []
}
""")
}
// Serve files from a directory
server.use(staticDirectory: "./public")
// Multiple static directories
server.use(staticDirectory: "./assets")
server.use(staticDirectory: "./uploads")
SwiftWebServer is @MainActor-isolated and Sendable. Configuration is
read-only after listen(_:) is called β registering routes, middleware, or
static directories on a running server traps with a precondition failure.
let server = SwiftWebServer()
atom2ueki/SwiftWebServer is a public repo on GitHub by atom2ueki. swift based web server.
It declares the MIT license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-08-29. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
Take My Repo cannot say: it does not audit code and has not run SwiftWebServer. What is known comes from GitHub. It declares the MIT license on GitHub. Its last change was on 2026-08-29. It has 3 stars, which measure popularity, not safety. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read the source before you run it. With "Take it", your AI agent shows each step and asks you before running it; README text is treated as data, not as instructions.