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
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 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
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
💧 A server-side Swift web framework.

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

Vapor 22.4k Jan 7, 2023
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
Meet Corvus, the first strongly declarative server-side framework.

Corvus Corvus is the first truly declarative server-side framework for Swift. It provides a declarative, composable syntax which makes it easy to get

null 42 Jun 29, 2022
Super lightweight web framework in Swift based on SWSGI

Ambassador Super lightweight web framework in Swift based on SWSGI Features Super lightweight Easy to use, designed for UI automatic testing API mocki

Envoy 170 Nov 15, 2022
A Swift Multiplatform Single-threaded Non-blocking Web and Networking Framework

Serverside non-blocking IO in Swift Ask questions in our Slack channel! Lightning (formerly Edge) Node Lightning is an HTTP Server and TCP Client/Serv

SkyLab 316 Oct 6, 2022
Evented I/O streams for Swift

Noze.io "Das Haus das Verrückte macht." Noze.io is an attempt to carry over the Node.js ideas into pure Swift. It uses libdispatch for event-driven, n

The Noze Consortium 305 Oct 14, 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
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
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 Jan 5, 2023
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
A repository for showcasing my knowledge of the Swift programming language, and continuing to learn the language.

Learning Swift (programming language) I know very little about programming in the Swift programming language. This document will go over all my knowle

Sean P. Myrick V19.1.7.2 2 Nov 8, 2022
A repository for showcasing my knowledge of the Objective-C++ programming language, and continuing to learn the language.

Learning Objective-C-Plus-Plus I hardly know anything about the Objective-C++ programming language. This document will go over all of my knowledge of

Sean P. Myrick V19.1.7.2 3 Nov 8, 2022
A repository for showcasing my knowledge of the Objective-C programming language, and continuing to learn the language.

Learning Objective-C I hardly know anything about the Objective-C programming language. This document will go over all of my knowledge of the Objectiv

Sean P. Myrick V19.1.7.2 3 Nov 8, 2022
Imagine Engine - a fast, high performance Swift 2D game engine for Apple's platforms

Welcome to Imagine Engine, an ongoing project that aims to create a fast, high performance Swift 2D game engine for Apple's platforms that is also a j

John Sundell 1.8k Jan 3, 2023
Palico Engine: Metal-Based Game Engine in Swift 🐑

Palico Engine: Metal-Based Game Engine in Swift ?? Implement a game engine on macOS using Metal API. Still in development. Currently I am working on a

Junhao Wang 24 Dec 1, 2022
RSNetworking is a networking library written entirly for the Swift programming language.

RSNetworking is a networking library written entirly for the Swift programming language.

null 18 Feb 25, 2018
A parser combinator library written in the Swift programming language.

SwiftParsec SwiftParsec is a Swift port of the Parsec parser combinator library. It allows the creation of sophisticated parsers from a set of simple

David Dufresne 219 Nov 6, 2022