Tiny http server engine written in Swift programming language.

Overview

Platform Swift Protocols CocoaPods Carthage Compatible

What is Swifter?

Tiny http server engine written in Swift programming language.

Branches

* stable - lands on CocoaPods and others. Supports the latest non-beta Xcode and SPM. Stable.

* master - stable branch plus experimental web-framework layer.

* 2.0 - next version of Swifter (async IO). Experimental.

How to start?

let server = HttpServer()
server["/hello"] = { .ok(.htmlBody("You asked for \($0)"))  }
server.start()

How to load HTML by string?

let server = HttpServer()
server[path] = { request in
    return HttpResponse.ok(.text("<html string>"))
}
server.start()

How to share files?

let server = HttpServer()
server["/desktop/:path"] = shareFilesFromDirectory("/Users/me/Desktop")
server.start()

How to redirect?

let server = HttpServer()
server["/redirect"] = { request in
  return .movedPermanently("http://www.google.com")
}
server.start()

How to HTML ?

let server = HttpServer()
server["/my_html"] = scopes { 
  html {
    body {
      h1 { inner = "hello" }
    }
  }
}
server.start()

How to WebSockets ?

let server = HttpServer()
server["/websocket-echo"] = websocket(text: { session, text in
  session.writeText(text)
}, binary: { session, binary in
  session.writeBinary(binary)
})
server.start()

CocoaPods? Yes.

use_frameworks!

pod 'Swifter', '~> 1.5.0'

Carthage? Also yes.

github "httpswift/swifter" ~> 1.5.0

Swift Package Manager.

import PackageDescription

let package = Package(
    name: "MyServer",
    dependencies: [
        .package(url: "https://github.com/httpswift/swifter.git", .upToNextMajor(from: "1.5.0"))
    ]
)

Docker.

docker run -d -p 9080:9080 -v `pwd`:/Swifter -w /Swifter --name Swifter swift bash -c "swift run"
Comments
  • Compilation in Xcode 12 beta fails with version 1.4.7 from SPM

    Compilation in Xcode 12 beta fails with version 1.4.7 from SPM

    Hi, when I try to compile for iOS Simulator a project where I use Swifter 1.4.7 (via SPM) with Xcode 12, I get the following error:
    /Path/To/Project/SourcePackages/checkouts/swifter/XCode/Sources/Socket+File.swift:26:61: Generic parameter 'Element' could not be inferred

    image

    The version from stable works without issues.

    opened by lecksfrawen 28
  • Sinatra

    Sinatra

    Are you planning to or know of any efforts to create a Swift framework inspired by Ruby's Sinatra?

    I see this has some similarities but wondered if you planned to take it further?

    opened by jchannon 17
  • Swift Compiler Error: cannot invoke 'subscript'

    Swift Compiler Error: cannot invoke 'subscript'

    After fixing some of the compile issues on Xcode 6 (mostly dealing with NSError initializers), I'm getting the following error:

    <unknown>:0: error: cannot invoke 'subscript' with an argument list of type '($T5, Builtin.RawPointer)'
    <unknown>:0: error: cannot invoke 'subscript' with an argument list of type '($T5, Builtin.RawPointer)'
    
    opened by AquaGeek 14
  • What is the correct way to link an external style sheet file

    What is the correct way to link an external style sheet file

    Hi, I created a /Resources/Web directory as "Folder references" under my project root directory. The structure is shown below:

    -Web:
      -css:
        bootstrap.min.css
      -js:
        index.html
    

    The html can be retrieved with html = NSData(contentsOfFile:"\(rootDir)/Web/index.html") and shown in the browser, but linking to external css failed in the Chrome console.

    Below is the link tag in my index.html. I am wondering why it not works.

    <head>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    ...
    </head>
    

    If above is not an option, does that mean css files also need to be retrieved like html files and then insert the css text into the head place of the html text, and return?

    Thanks very much! Roman

    opened by roman-yu 12
  • How can I use it for upload a file to my device

    How can I use it for upload a file to my device

    If I change the login.html, for example: add a 'file' type input and change the form enctype to 'multipart/form-data' . How can I handler the request and write a (or multiple) file to document folder?

    opened by elepone 12
  • Regression on v1.4.6

    Regression on v1.4.6

    Hello! I am experiencing a regression on v1.4.6.

    Consider the following code.

    // Path Declaration
    var path: String {
            switch self {
            case .postOnboardingDocCheckFinishSuccess:
                return "onboarding/doc-check/finish"
            case .postOnboardingDocCheckStartSuccess:
                return "onboarding/doc-check/start"
            default:
                return "onboarding"
            }
        }
    
    // Path registration
    enum Method {
        case DELETE
        case PATCH
        case HEAD
        case POST
        case GET
        case PUT
    }
    
    protocol EndPoint {
        var method: Method { get }
        var path: String { get }
        var response: ((HttpRequest) -> HttpResponse) { get }
    }
    
    protocol JSONFileRepresentable {
        var fileName: String { get }
    }
    
    class Router {
        let server: HttpServer
        
        init() {
            server = HttpServer()
        }
        
        func stop() {
            server.stop()
        }
        
        func start() {
            try! server.start()
        }
        
        func setUp(with endPoints: [EndPoint]) {
            endPoints.forEach({
                switch $0.method {
                case .GET:
                    server.GET[$0.path] = $0.response
                case .POST:
                    server.POST[$0.path] = $0.response
                case .PUT:
                    server.PUT[$0.path] = $0.response
                case .DELETE:
                    server.DELETE[$0.path] = $0.response
                default:
                    fatalError("Method not yet supported")
                }
            })
        }
    }
    

    Registering only Onboarding success. Calls the response block normally. But registering all 3 paths makes onboarding to return 404 not found. This is part of a testing suite and it started falling after updating to v1.4.6

    It works fine on v1.4.5

    opened by sonic555gr 10
  • server.start() doesn't actually do anything

    server.start() doesn't actually do anything

    When trying to run the following code (more or less copied from the readme)

    import Swifter
    import Foundation
    
    func createServer() -> HttpServer {
      let server = HttpServer()
    
      server["/hello"] = { request in .ok(.text("Hey")) }
    
      return server
    }
    
    
    let myServer = createServer()
    try myServer.start()
    

    The HTTP server doesn't actually start. Like, I can run swift build just fine, but actually executing the compiled binary just starts and exits normally. I would assume this isn't supposed to happen, but I can't find anything in the documentation about how one should actually start the server (the documentation also fails to mention that you need to have try before server.start()).

    bug 
    opened by jalavosus 10
  • How do I add different responses based on request GET parameters?

    How do I add different responses based on request GET parameters?

    So is there a way to make different responses for different parameters? Im using Swifter to mock server responses and it would be great to response differently based on request’ GET parameters, but I can’t really figure how to add such responses

    opened by AndrewSad 10
  • compile errors with swift 4.1 and xcode 9.3

    compile errors with swift 4.1 and xcode 9.3

    I am trying to update my app from swift 3 to swift for 4 and getting compile errors on Scopes.swift on scope() "Missing argument for parameter #1 in call, public typealias Closure = (Void) -> Void "When calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?"

    I created a small test app with just the swifter pod and getting the same thing.

    I am using xcode 9.3, in build settings I have tried setting the Swift Language Version to unspecified and Swift 4.1 but I am getting the same errors when I do a Product clean and then Product Build My podfile has: pod 'Swifter', '~> 1.3.3'

    opened by benchd 9
  • Not actually an issue just a question. How to obtain the request ip address?

    Not actually an issue just a question. How to obtain the request ip address?

    Thank you for making Swifter available for everyone. I apologize I don't mean to use you as a support agent, but I was wondering, is there any way to obtain the request ip address?

    I wanted to ask one more thing, in my case I need a small web server to send and receive plain text and not to share files or webpages. Is swifter ideal for this scenario? I'm sorry I'm not very versed in this matter.

    opened by oncre 9
  • releaseAcceptSocket() doesn't cut availability of the server

    releaseAcceptSocket() doesn't cut availability of the server

    The stop() / releaseAcceptSocket() methods don't seem to shut the server down. It is still available after I called the method. Is there a way to shut it completely down or did I misinterpreted the meaning of those? Thank you!

    opened by RGreinacher 8
  • Can the development on this package be sponsored?

    Can the development on this package be sponsored?

    This library provides useful functionality. I see there's quite a lot of issues open. It looks like this library is widely used, yet isn't maintained for quite some time... Is there a plan to provide future maintenance for this library? Can we support the development of this package?

    opened by bielikb 0
  • Fix body-writer exception causes hang

    Fix body-writer exception causes hang

    A sufficiently complex body-writer may not be able to complete writing the body, and the only practical approach is to throw an exception.

    Exceptions are normally thrown from body-writers when the socket is closed by the remote peer.

    If a Raw response body-writer throws an exception before completing the body the http session will be left out of sync and will hang indefinitely waiting to read the next request. The fix results in the socket being closed and not attempting to read the next request when an error occurs. If a content-length is provided then the network error can be detected by the remote peer, otherwise a truncated body is returned to the client.

    opened by mrstux 1
  • Enhancement request: Swifter to label .wasm files as

    Enhancement request: Swifter to label .wasm files as "application/wasm" when it serves them

    Dear Swifter Developers,

    I am a novice javascript user who uses the Swifter tiny http server engine in the iOS app "World Wide Web Sever". It would helpful in the future if Swifter labeled .wasm files as MIME type "application/wasm" when it serves them to help browsers do .wasm instantiate streaming.

    Thank you for the considering this enhancement. :-)

    opened by SugarRayLua 0
  • Building release is extremely slow

    Building release is extremely slow

    It takes like 2 minutes to build the release version of Swifter. Building the debug version takes a normal amount of time. I don't know if this is a Swift bug or a bug in this project.

    opened by GameParrot 0
  • 404 Not Found

    404 Not Found

    Hello, I have a task of "reviving" someone else iOS app which uses your (Swifter) library. I've encountered quite weird problem:

    Here is the setup:

    • application has files in some location (lets say /serve on the phone (there is a folder called webapp and inside is index.html and folder res with some css files)
    • application creates server
    server["/:path"] = shareFilesFromDirectory(servePath)
    # servePath = "...serve/"
    
    • application presents webview pointing request to http://localhost:8080/webapp/index.html

    Main problem is that I get Status code: 404

    Here are my findings:

    • files are there - I'm listing whole folder tree and printing content of index.html
    • swifter (and webview) works I replace
    server["/:path"] = shareFilesFromDirectory(servePath)
    

    with

    server["/webapp/index.html"] = { .ok(.htmlBody("You asked for \($0)"))  }
    

    and I get You ask for... in webview

    • if I add servePath /webapp and the end and remove it from webview request (making it http://localhost:8080/index.html) - webpage loads with out no style. I then went in with inspector and saw that all other files get 404 (so for example http://localhost:8080/src/main.css)]

    Is there something with directories that is blocking (permissions or sth)?

    Thx for the help

    opened by ajitam 0
Releases(1.5.0)
  • 1.5.0(Sep 26, 2020)

  • 1.5.0-rc.1(Sep 17, 2020)

    Removed

    • Support for the iOS 8 deployment target. (#462) by @Vkt0r

    Added

    • Add the trailing_whitespace rule in Swiftlint and autocorrect all the source files. (#421) by @Vkt0r
    • Update the project for Xcode 11.1. (#438) by @Vkt0r
    • Add optional 'Content-Type' to Data HttpResponse. (#450) by @SoftwareEngineerChris
    • Support Xcode 12 and Swift 5+. (#462) by @Vkt0r

    Changed

    • Turn HttpServer and HttpServerIO into open classes to allow for more customization. (#443) by @cobbal
    • Set the version of the HTTP Server based in the project version in the Info.plist for macOS, iOS and tvOS platforms. (#416) by @Vkt0r
    • Update HttpParser so it percent-encodes the URL components before initializing URLComponents. (#423) by @nejcvivod
    • Update SwifterTestsHttpParser with a test for parsing bracketed query strings. (#423) by @nejcvivod
    • Use swift_version CocoaPods DSL. (#425) by @dnkoutso
    • Fix compiler warnings in Socket+File.swift for iOS, tvOS, and Linux platforms by using withUnsafeBytes rather than & to get a scoped UnsafeRawPointer (#445) by @kbongort.
    • Fix tests on linux by importing FoundationNetworking for NSURLSession APIs. (#446) by @kbongort
    • Replace CircleCI for continuous integration in favor of Github Actions. (#446) by @Vkt0r
    Source code(tar.gz)
    Source code(zip)
  • 1.4.7(Jun 10, 2019)

    Added

    • A new CHANGELOG.md to keep track of changes in the project. (#385) by @Vkt0r
    • Added Danger and Swiftlint to the project. (#398) by @Vkt0r
    • Added the following to Scopes: manifest, ontouchstart, dataText. (#410) by @apocolipse
    • Added htmlBody(String) to HttpResonse as a compability case for the changed html(String) case. (#410) by @apocolipse

    Fixed

    • An issue causing a crash regarding a thread race condition. (#399) by @Vkt0r

    • An issue in the HttpRouter causing issues to handle routes with overlapping in the tail. (#379, #382) by @Vkt0r

    • Fixes build errors by excluding XC(UI)Test files from regular targets. (#397) by @ChristianSteffens

    • Fixes HttpRequest.path value to be parsed without query parameters. (#404) by @mazyod

    • Fixes the issue of missing Content-Length header item when shareFilesFromDirectory is being used to share files. (#406) by @nichbar

    Changed

    • Performance: Batch reads of websocket payloads rather than reading byte-by-byte. (#387) by @lynaghk
    • Podspec source_files updated to match source file directory changes. (#400) by @welsonpan
    • Refactor: Use Foundation API for Base64 encoding. (#403) by @mazyod
    • Refactor: Use URLComponents for HttpRequest path and query parameters parsing #404) by @mazyod
    • HttpResponse functions statusCode() and reasonPhrase changed to computed variables instead of functions, and made public (No impact on existing usage as it was previously internal). (#410) by @apocolipse
    • Adjusted the associated type of enum case HttpResponseBody.json from AnyObject to Any to allow Swift dictionaries/arrays without converting to their Objective-C counterparts. (#393) by @edwinveger
    • HttpResponse: html requires now a complete html-string, not only the body-part.
    • Include the CHANGELOG.md and README.md in the Xcode-Project for easy access / changes.

    Removed

    Source code(tar.gz)
    Source code(zip)
Owner
Tiny http server engine written in Swift
null
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

Always Right Institute 116 Aug 6, 2022
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
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
C-Xpress is a modern c-like object oriented programming language running on top of the .NET framework

C-Xpress Programming Language The cxpress programming language is a High Level object oriented programming language running on the .NET Framework C-Xp

null 2 Jan 12, 2022
A dead simple programming language.

checked Checked is a dead simple programming language. Variable declarations with type inference func main() { let constantVariable = 5 var va

Oliver Letterer 2 Oct 21, 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
Super lightweight async HTTP server library in pure Swift runs in iOS / MacOS / Linux

Embassy Super lightweight async HTTP server in pure Swift. Please read: Embedded web server for iOS UI testing. See also: Our lightweight web framewor

Envoy 540 Dec 15, 2022
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
Language Server Protocol (LSP) client for Swift

LanguageClient This is a Swift library for abstracting and interacting with language servers that implement the Language Server Protocol. It is built

Chime 35 Jan 1, 2023
A tiny library makes uploading and downloading easier

Features uploading/downloading multiple files concurrently or sequentially grouping tasks with awesome custom operators (||| and -->) supports backgro

Le Van Nghia 450 Nov 19, 2022
Http Request wrapper written in Swift

Net Net is a HttpRequest wrapper written in Swift Features GET, POST, PUT, DELETE method Powerful request params: nested params, number, string, dic,

Le Van Nghia 304 Jun 29, 2022
ServiceData is an HTTP networking library written in Swift which can download different types of data.

ServiceData Package Description : ServiceData is an HTTP networking library written in Swift which can download different types of data. Features List

Mubarak Alseif 0 Nov 11, 2021
Swift Express is a simple, yet unopinionated web application server written in Swift

Documentation <h5 align="right"><a href="http://demo.swiftexpress.io/">Live ?? server running Demo <img src="https://cdn0.iconfinder.com/data/icons/

Crossroad Labs 850 Dec 2, 2022
Plugin for authorization with Facebook for Godot Game Engine (iOS)

GodotFacebookAuth Plugin for authorization with Facebook for Godot Game Engine (iOS) Supports iOS deployment target >= 10.0 Supports Godot version >=

Oleksandr Kurtsev 6 Sep 20, 2022
Fizz Buzz is a very simple programming task, asked in software developer job interviews.

FizzBuzz Fizz Buzz is a very simple programming task, asked in software developer job interviews. A typical round of Fizz Buzz can be: Write a program

Allan Garcia 1 Jun 6, 2022