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 light-weight server-side service framework written in the Swift programming language.

Smoke Framework The Smoke Framework is a light-weight server-side service framework written in Swift and using SwiftNIO for its networking layer by de

Amazon 1.4k Dec 22, 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
💧 A server-side Swift HTTP web framework.

Vapor is an HTTP web framework for Swift. It provides a beautifully expressive and easy-to-use foundation for your next website, API, or cloud project

Vapor 22.4k Jan 3, 2023
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 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 Dec 27, 2022
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
A small, lightweight, embeddable HTTP server for Mac OS X or iOS applications

CocoaHTTPServer CocoaHTTPServer is a small, lightweight, embeddable HTTP server for Mac OS X or iOS applications. Sometimes developers need an embedde

Robbie Hanson 5.5k Jan 7, 2023
GCDWebServer is a modern and lightweight GCD based HTTP 1.1 server designed to be embedded in iOS, macOS & tvOS apps.

GCDWebServer is a modern and lightweight GCD based HTTP 1.1 server designed to be embedded in iOS, macOS & tvOS apps. It was written from scr

Pierre-Olivier Latour 6.3k Dec 27, 2022
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
A template to get vapor working on Google App Engine

Swift Vapor App Engine This is a template to get vapor working on Google App Engine. Really all that's special is that it has a Dockerfile (included w

Michael 2 Oct 10, 2022
HTTP Implementation for Swift on Linux and Mac OS X

Swift HTTP Server Simple HTTP implementation for Swift using POSIX socket API. Running on Mac OS X and Linux. For Mac users: You can install new Swift

Huy 451 Jul 28, 2022
A lightweight library for writing HTTP web servers with Swift

Taylor Disclaimer: Not actively working on it anymore. You can check out some alternatives Swift 2.0 required. Working with Xcode 7.1. Disclaimer: It

Jorge Izquierdo 925 Nov 17, 2022
Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)

Perfect: Server-Side Swift 简体中文 Perfect: Server-Side Swift Perfect is a complete and powerful toolbox, framework, and application server for Linux, iO

PerfectlySoft Inc. 13.9k Dec 29, 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
Simple server APIs in Swift

Simple server APIs in Swift

null 4 Apr 25, 2022
Lightweight library for web server applications in Swift on macOS and Linux powered by coroutines.

Why Zewo? • Support • Community • Contributing Zewo Zewo is a lightweight library for web applications in Swift. What sets Zewo apart? Zewo is not a w

Zewo 1.9k Dec 22, 2022
High Performance (nearly)100% Swift Web server supporting dynamic content.

Dynamo - Dynamic Swift Web Server Starting this project the intention was to code the simplest possible Web Server entirely in Swift. Unfortunately I

John Holdsworth 68 Jul 25, 2022
Reliable Server Side Swift ✭ Make Apache great again!

mod_swift mod_swift is a technology demo which shows how to write native modules for the Apache Web Server in the Swift 3 programming language. The de

The ApacheExpress Alliance 174 Oct 22, 2022
PillowTalk - An iOS & SwiftUI server monitor tool for linux based machines using remote proc file system with script execution.

An iOS & SwiftUI server monitor tool for linux based machines using remote proc file system with script execution.

Lakr Aream 416 Dec 16, 2022