HttpServer

main

Simple HTTP Server built on SwiftNIO.
miguelfermin/async-http-server

HttpServer

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

Example

  1. Create Router
let router = Router()
  1. Add Middleware, as many as needed, and called in the order they're added.
router.use(
    cors(allowOrigin: "*")
)
  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
    guard let device: Device = req.model() else {
        res.write(DeviceError.addError, status: .badRequest)
        return
    }
    do {
        try DataSource.addDevice(device)
        res.write(device, status: .ok)
    } catch {
        res.write(error.localizedDescription, status: .internalServerError)
    }
}

// DELETE
router.delete("/v1/device") { req, res, _ in
    guard let device: Device = req.model() else {
        res.write(DeviceError.addError, status: .badRequest)
        return
    }
    do {
        try DataSource.deleteDevice(id: device.id)
        res.write("Device deleted", status: .ok)
    } catch {
        res.write(DeviceError.deleteError, status: .internalServerError)
    }
}
  1. Start Server
let server = HttpServer()
let host = "localhost"
let port = 1338

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

References:

Description

  • Swift Tools 5.3.0
View More Packages from this Author

Dependencies

Last updated: Sat Nov 02 2024 10:20:50 GMT-0900 (Hawaii-Aleutian Daylight Time)