A simple GCD based HTTP client and server, written in 'pure' Swift

Overview

SwiftyHTTP

Note: I'm probably not going to update this any further - If you need a Swift networking toolset for the server side, consider: Macro.swift.

A simple GCD based HTTP library for Swift. This project is 'pure' Swift/C, it does not use any bridged Objective-C classes.

SwiftyHTTP is a demo on how to integrate Swift with raw C APIs. More for stealing Swift coding ideas than for actually using the code in a real project. In most real world Swift apps you have access to Cocoa, use it.

Note: This is just my second Swift project. Any suggestions on how to improve the code are welcome. I expect lots and lots :-)

First things first: Samples

Server:

let httpd = HTTPServer()
  .onRequest {
    rq, res, con in
    res.bodyAsString = "<h2>Always Right, Never Wrong!</h2>"
    con.sendResponse(res)
  }
  .listen(1337)

Server using the Node.JS like Connect bonus class:

let httpd = Connect()
  .use { rq, res, _, next in
    print("\(rq.method) \(rq.url) \(res.status)")
    next()
  }
  .use("/hello") { rq, res, con, next in
    res.bodyAsString = "Hello!"
    con.sendResponse(res)
  }
  .use("/") { rq, res, con, next in
    res.bodyAsString = "Always, almost sometimes."
    con.sendResponse(res)
  }
  .listen(1337)

Client (do not use this, use NSURLSession!):

GET("http://www.apple.com/")
  .done {
    print()
    print("request  \($0)")
    print("response \($1)")
    print("body:\n\($1.bodyAsString)")
  }
  .fail {
    print("failed \($0): \($1)")
  }
  .always { print("---") }

Targets

Updated to use Swift v0.2.2 (aka Xcode 7.3).

The project includes three targets:

  • SwiftyHTTP
  • SwiftyServer
  • SwiftyClient

I suggest you start out looking at the SwiftyServer.

SwiftyHTTP

A framework containing the HTTP classes and relevant extensions. It has a few 'subprojects':

  • Foundation
  • Sockets
  • Parser
  • HTTP
Foundation

This has just the 'RawByteBuffer' class. Which is kinda like a UInt8 array. I bet there are better ways to implement this! Please suggest some! :-)

Also a few - highly inefficient - extensions to convert between String's and CString's. I would love some suggestions on those as well.

But remember: NSxyz is forbidden for this venture! :-)

Sockets

Just a local copy of the SwiftSockets project - I wish GIT had proper externals ;-) (https://github.com/AlwaysRightInstitute/SwiftSockets)

Parser

This uses the C HTTP parser which is also used in Node.JS. It had to modified a tinsy bit - the Swift C bridge doesn't support bitfields. Those had to be removed from the http_parser struct.

It also contains the main request/response classes: HTTPRequest and HTTPResponse, both subclasses of HTTPMessage. And enums for HTTP status values (like πŸ’°Required) and request methods (GET etc).

HTTP

HTTPConnectionPool is an abstract base class and manages open connections, either incoming or outgoing. The HTTPConnection sits on top of the SwiftSockets and manages one HTTP connection (it connects the socket to the parser).

HTTPServer is the server class. Uses SwiftSockets to listen for incoming connections. See above for a sample.

As a bonus - this also has a tiny Connect class - which is modelled after the Node.JS Connect thingy (which in turn is apparently modelled after RoR Rack). It allows you to hook up a set of blocks for request processing, instead of having just a single entry point. Not sure I like that stuff, but it seems to fit into Swift quite well. Find a sample above.

Finally there is a simple HTTP client. Doesn't do anything fancy. Do not - ever

  • use this. Use NSURLSession and companions.

SwiftyServer

Great httpd server - great in counting the requests it got sent. This is not actually serving any files ;-) Comes along as a Cocoa app. Compile it, run it, then connect to it in the browser via http://127.0.0.1:1337/Awesome-O!

SwiftyClient

Just a demo on how to do HTTP requests via SwiftyHTTP. No, it doesn't do JSON decoding and such.

Again: You do NOT want to use it in a real iOS/OSX app! Use NSURLSession and companions - it gives you plenty of extra features you want to have for realz.

Goals

  • Max line length: 80 characters
  • Great error handling
    • PS style great error handling
    • print() error handling
    • Swift 2 try/throw/catch
      • Real error handling
  • Twisted (no blocking reads or writes)
    • Async reads and writes
      • Never block on reads
      • Never block on listen
    • Async connect()
  • No NS'ism
  • Use as many language features Swift provides
    • Generics
      • Generic function
      • typealias
    • Closures
      • weak self
      • trailing closures
      • implicit parameters
    • Unowned
    • Extensions on structs
    • Extensions to organize classes
    • Protocols on structs
    • Swift 2 protocol extensions
    • Tuples
    • Trailing closures
    • @Lazy
    • Pure Swift weak delegates via @class
    • Optionals
      • Implicitly unwrapped optionals
    • Convenience initializers
    • Failable initializers
    • Class variables on structs
    • CConstPointer, CConstVoidPointer
      • withCString {}
    • UnsafePointer
    • sizeof()
    • Standard Protocols
      • Printable
      • BooleanType (aka LogicValue)
      • OutputStreamType
      • Equatable
        • Equatable on Enums with Associated Values
      • Hashable
      • SequenceType (GeneratorOf)
      • Literal Convertibles
        • StringLiteralConvertible
        • IntegerLiteralConvertible
    • Left shift AND right shift
    • Enums on steroids
      • RawRepresentable
    • Dynamic type system, reflection
    • Operator overloading
    • UCS-4 identifiers ( πŸ” πŸ” πŸ” )
    • RTF source code with images and code sections in different fonts
    • Nested classes/types
    • Patterns
      • Use wildcard pattern to ignore value
    • @autoclosure
    • unsafeBitCast (was reinterpretCast)
    • final
    • Nil coalescing operator
    • dynamic
    • Swift 2
      • availability
      • guard
      • defer
      • C function pointers
      • debugPrint
      • lowercaseString
    • #if os(Linux)
    • #if swift(>=2.2)
  • Swift Package Manager
    • GNUmakefile support
  • Linux support

Why?!

This is an experiment to get acquainted with Swift. To check whether something real can be implemented in 'pure' Swift. Meaning, without using any Objective-C Cocoa classes (no NS'ism). Or in other words: Can you use Swift without writing all the 'real' code in wrapped Objective-C? :-)

Contact

@helje5 | [email protected]

You might also like...
DispatchSource based socket framework written in pure Swift

SwiftDSSocket Overview SwiftDSSocket is a purely swift based asynchronous socket framework built atop DispatchSource. Function signatures are pretty m

Cross-platform JsonRPC client implementation with HTTP and WebSocket support

JsonRPC.swift Cross-platform JsonRPC client implementation with HTTP and WebSocket support Getting started Installation Package Manager Add the follow

A barebones Swift HTTP client with automatic JSON response parsing.

HTTP Client A barebones Swift HTTP client with automatic JSON response parsing. Installation Add HTTP Client as a dependency through Xcode or directly

HTTPClient - HTTP Client With Swift

HTTPClient Ex. Search Repository import HTTPClient let url: URL = .init(string:

A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS
A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS

A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS Built by Tijme Gommers – Buy me a coffee via P

 Postie - The Next-Level HTTP API Client using Combine
Postie - The Next-Level HTTP API Client using Combine

Postie - The Next-Level HTTP API Client using Combine Postie is a pure Swift library for building URLRequests using property wrappers.

πŸ“‘ RealHTTP is a lightweight yet powerful client-side HTTP library.
πŸ“‘ RealHTTP is a lightweight yet powerful client-side HTTP library.

RealHTTP RealHTTP is a lightweight yet powerful client-side HTTP library. Our goal is make an easy to use and effortless http client for Swift. Featur

The HTTP library used by the Spotify iOS client
The HTTP library used by the Spotify iOS client

Authentication and back-off logic is a pain, let's do it once and forget about it! This is a library that allows you to centralise this logic and forg

πŸ”Œ  Non-blocking TCP socket layer, with event-driven server and client.
πŸ”Œ Non-blocking TCP socket layer, with event-driven server and client.

Original authors Honza Dvorsky - http://honzadvorsky.com, @czechboy0 Matthias Kreileder - @matthiaskr1 At the request of the original authors, we ask

Comments
  • feature/swift2

    feature/swift2

    I just used carthage to try to pull the swift2 branch and it looks like there are now shared schemes - can you update the schemes so they can be carthage built?

    Thanks

    opened by jeeftor 1
  • Fix broken headings in Markdown files

    Fix broken headings in Markdown files

    GitHub changed the way Markdown headings are parsed, so this change fixes it.

    See bryant1410/readmesfix for more information.

    Tackles bryant1410/readmesfix#1

    opened by bryant1410 0
  • made universal iOS/OS X framework

    made universal iOS/OS X framework

    Makes the framework build for OS X and iOS. We have to wait for OS X 10.10 for it to build properly, but I have tried this successfully with other projects and it works.

    opened by colemancda 0
  • Parser gets confused on 1st connects, reporting invalid method

    Parser gets confused on 1st connects, reporting invalid method

    When running the server for the first time, it quite often (always?) complains that the 1st incoming request has an invalid HTTP method and the parser is consuming no bytes. No idea why, need to debug.

    opened by helje5 0
Owner
Always Right Institute
The Always Right Institute has been established to encourage a culture of being right. As well as being right. Always.
Always Right Institute
A simple HTTP server written in Swift

http4swift http4swift is a tiny HTTP server library for Nest-compatible applications. This project is unstable, and the API might be changed at anytim

Shun Takebayashi 27 Jun 29, 2022
Tiny http server engine written in Swift programming language.

What is Swifter? Tiny http server engine written in Swift programming language. Branches * stable - lands on CocoaPods and others. Supports the latest

null 3.6k Dec 31, 2022
Lightweight, flexible HTTP server framework written in Swift

Hummingbird Lightweight, flexible server framework written in Swift. Hummingbird consists of three main components, the core HTTP server, a minimal we

Hummingbird 245 Dec 30, 2022
Http - Demo for Http Layer

http Example To run the example project, clone the repo, and run pod install fro

null 0 Jan 24, 2022
A Swift web framework and HTTP server.

A Swift Web Framework and HTTP Server Summary Kitura is a web framework and web server that is created for web services written in Swift. For more inf

Kitura 7.6k Jan 6, 2023
Swift HTTP server using the pre-fork worker model

Curassow Curassow is a Swift Nest HTTP Server. It uses the pre-fork worker model and it's similar to Python's Gunicorn and Ruby's Unicorn. It exposes

Kyle Fuller Archive 397 Oct 30, 2022
libuv base Swift web HTTP server framework

Notice Trevi now open a Trevi Community. Yoseob/Trevi project split up into respective Trevi, lime, middlewares and sys packages at our community. If

leeyoseob 46 Jan 29, 2022
A very basic proof-of-concept Swift HTTP server that does not require Foundation

Swift Server Introduction This is very rough and basic HTTP server written in Swift without using Foundation. This is partially based on the Swifter r

Cezary Wojcik 55 Apr 27, 2022
FlyingFox - a lightweight HTTP server built using Swift Concurrency

Usage Credits Introduction FlyingFox is a lightweight HTTP server built using Swift Concurrency. The server uses non blocking BSD sockets, handling ea

Simon Whitty 262 Dec 24, 2022
Swift backend / server framework (Pure Swift, Supports Linux)

NetworkObjects NetworkObjects is a #PureSwift backend. This framework compiles for OS X, iOS and Linux and serves as the foundation for building power

Alsey Coleman Miller 258 Oct 6, 2022