Swiftpack.co -  miguelfermin/HttpServer as Swift Package
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
miguelfermin/HttpServer
Simple HTTP Server built on SwiftNIO and inspired by Go's http package
.package(url: "https://github.com/miguelfermin/HttpServer.git", from: "0.1.0")

HttpServer

Simple HTTP Server built with SwiftNIO and inspired by Go's http package

Example

  1. Create Router
let router = Router()
  1. Add Middleware
router.use(
    Middleware.cors(allowOrigin: "*"),
    myCustomMiddleware
)
  1. Add Handlers
// GET List
router.get("/v1/devices") { req, res, _ in
    let devices = DataSource.fetchDevices()
    res.write(devices, status: .ok)
}

// GET One
router.get("/v1/device") { req, res, _ in
    guard let param = req.param("id"), let id = Int(param) else {
        res.write("Missing query param \"id\"", status: .badRequest)
        return
    }
    guard let device = DataSource.device(id: id) else {
        res.write("Device not found", status: .notFound)
        return
    }
    res.write(device, status: .ok)
}

// POST
router.post("/v1/devices") { req, res, _ in
    do {
        let device: Device = try req.model()
        let savedDevice = try DataSource.addDevice(device)
        res.write(savedDevice, status: .ok)
    } catch RequestDecodingError.info(let info) {
        res.write(info, status: .badRequest)
    } catch SaveDeviceError.info(let info, let status) {
        res.write(info, status: status)
    } catch {
        res.write(error.localizedDescription, status: .internalServerError)
    }
}

// DELETE
router.delete("/v1/device") { req, res, _ in
    do {
        let device: Device = try req.model()
        try DataSource.deleteDevice(id: device.id)
        res.write("Device deleted", status: .ok)
    } catch RequestDecodingError.info(let info) {
        res.write(info, status: .badRequest)
    } catch DeleteDeviceError.info(let info, let status) {
        res.write(info, status: status)
    } catch {
        res.write(error.localizedDescription, status: .internalServerError)
    }
}
  1. Start Server
let server = Server()
let host = "localhost"
let port = 1338

try server.listenAndServe(host: host, port: port, handler: router)

References:

GitHub

link
Stars: 1
Last commit: 2 weeks ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Dependencies

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API