• This repository has been archived on 09/Jun/2022
  • Stars
    star
    117
  • Rank 301,828 (Top 6 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 10 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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]

More Repositories

1

SwiftSockets

A simple GCD based socket wrapper for Swift.
Swift
277
star
2

dockSwiftOnARM

Playing with dockerizing Swift for Raspberry Pi
Dockerfile
121
star
3

Shell

Module exposing Unix command line tools as Swift 5 @dynamicCallable functions
Swift
109
star
4

SwiftyWasmer

A Swift API for the Wasmer WebAssembly Runtime
Swift
52
star
5

SwiftObjCBridge

A Swift Objective-C Bridge implemented using @dynamicCallable
Swift
45
star
6

MicroExpress

A micro web server framework on top of the official Swift HTTP API
Swift
29
star
7

NWHTTPProtocol

An HTTP protocol implementation (an `NWProtocolFramer`) and a tiny HTTP server for Network.framework
C
25
star
8

swift-arm2mac-x-compile-toolchain

SPM toolchain to cross compile macOS Swift binaries on a Raspberry Pi (yes, you read that right)
Shell
12
star
9

SwiftXmlRpc

An XML-RPC protocol implementation for Swift
Swift
12
star
10

MacroCows

A Swift macro plugin that expands Strings into ASCII Cows, right at compile time.
Swift
12
star
11

GTKKit

Write GTK (GNOME) Applications in Objective-C
Objective-C
10
star
12

SwiftyExpat

Simple wrapper for the Expat XML parser.
C
9
star
13

http-c-vs-swift

Test performance of http-parser in Swift and C
Swift
6
star
14

WebPackMiniS

A super simple mini version of WebPack written in Swift
Swift
5
star
15

MultiCrap

Quick hack to square-crop a folder of images
Swift
5
star
16

SQLite3Schema

A Swift library to fetch the schema from a SQLite3 database.
Swift
4
star
17

wren-swift

The wren scripting language as a Swift package, w/ some Swift API wrappers
C
4
star
18

libFoundation

An Objective-C Foundation library
Objective-C
2
star
19

helje5

The GitHub Home of Helge Heß
2
star
20

StaticCMS

GETobjects based static website generator
Java
1
star
21

swifter

Swifter - like Swift, but swift!
1
star
22

mod_objc1

Write Apache 1 modules in Objective-C via GNUstep/libFoundation
Objective-C
1
star