Coder Social home page Coder Social logo

httpswift / swifter Goto Github PK

View Code? Open in Web Editor NEW
3.8K 100.0 534.0 11.34 MB

Tiny http server engine written in Swift programming language.

License: BSD 3-Clause "New" or "Revised" License

Swift 97.33% Ruby 1.79% Objective-C 0.89%
server swift http web

swifter's Introduction

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"

swifter's People

Contributors

adamkaplan avatar christiansteffens avatar damian-kolakowski avatar damuellen avatar dependabot[bot] avatar ignatovsa avatar jcrate avatar jetforme avatar julien-c avatar ken-broadsheet avatar marcc-orange avatar mazyod avatar mbarnach avatar mhdhejazi avatar michaelenger avatar mtgto avatar nejcvivod avatar nickplee avatar palleas avatar pvzig avatar pyanfield avatar qvacua avatar soutaro avatar tanner0101 avatar tedgoddard avatar vkt0r avatar voynovia avatar welsonpan360 avatar yawaramin avatar yuri-qualtie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

swifter's Issues

Require latest version of Swift snapshot

This issue builds on issue #60.

A new dev snapshot of Swift has been released on December 10, with support for lots of Foundation constructs, including NSJSONSerialization.

For the time being, is it reasonable to require users of swifter to have the latest snapshot version of Swift?

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.

Serve a directory

Hello,
This is a great project but I can't get directory sharing to work. I'm trying to share static html and images. I saw there was an earlier issue about this but it seems that that solution doesn't work anymore, or am I wrong?

How to save data with upload?

Hi, I'm trying to use the upload function as shown in sample project. Anyway I'm not able to save the file uploaded in a folder in device.. I also can't find anything about this in source code.. Can you please help me? My actual code is:

   let server = HttpServer()

   let publicDir = NSBundle.mainBundle().resourcePath


   server["/resources/:file"] = HttpHandlers.directory(publicDir!)

   server.GET["/login"] = { r in
        if let rootDir = publicDir, html = NSData(contentsOfFile:"\(rootDir)/login.html") {
            var array = [UInt8](count: html.length, repeatedValue: 0)
            html.getBytes(&array, length: html.length)
            return HttpResponse.RAW(200, "OK", nil, { $0.write(array) })
        }
        return .NotFound
    }

    server["/hello"] = { r in
        if let rootDir = publicDir, html = NSData(contentsOfFile:"\(rootDir)/upload.html") {
            var array = [UInt8](count: html.length, repeatedValue: 0)
            html.getBytes(&array, length: html.length)
            return HttpResponse.RAW(200, "OK", nil, { $0.write(array) })
        }
        return .NotFound
    }

    server.POST["/upload"] = { r in
        var response = ""
        for multipart in r.parseMultiPartFormData() {
            response += "Name: \(multipart.name) File name: \(multipart.fileName) Size: \(multipart.body.count)<br>"
        }
        return HttpResponse.OK(.Html(response))
    }

    server.POST["/login"] = { r in
        let formFields = r.parseUrlencodedForm()
        return .MovedPermanently("/hello")
    }

    server.GET["/"] = { r in
        return .MovedPermanently("/login")
    }

    do {
        try server.start()
    } catch {
        print("Server start error: \(error)")
    }

thanks you very much

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?

Swift 2 version?

Hi Damian. I've got a project that needs an embedded HTTP server, and I thought I'd write it in Swift 2. I found swifter, but unfortunately Xcode 7b1 is unable to convert it completely automatically. Some additional re-write is necessary, and I'm not familiar enough with your code to be sure I'm doing it right.

Any chance you'll branch and update your code to Swift 2? Thanks!

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?

Is there a way to serve static html files from the local file system? ( OS X )

I am thinking of something maybe like the way GCD server does it? How would you do this in swifter?

https://github.com/swisspol/GCDWebServer

https://github.com/swisspol/GCDWebServer#serving-a-static-website

import "GCDWebServer.h"

int main(int argc, const char* argv[]) {
@autoreleasepool {

GCDWebServer* webServer = [[GCDWebServer alloc] init];
[webServer addGETHandlerForBasePath:@"/" directoryPath:NSHomeDirectory() indexFilename:nil cacheAge:3600 allowRangeRequests:YES];
[webServer runWithPort:8080];

}
return 0;
}

Support custom response headers

I want to set custom http response headers. I saw that headers are set in HttpResponse but there is no option to add custom ones, right?

I tried to work with extensions or inherit HttpResponse but it's an enum and limitied with inheration or extension. If HttpResponse would be a swift class it would be more extensionable for developers.

Automatic Content-Type?

It would be cool if using the .JSON, et al. response mechanism, it automatically set the response Content-Type header appropriately.

Thanks!

Will this work around fix the undefined htonl which causes the different port bug?

    let isLittleEndian = Int(OSHostByteOrder()) == OSLittleEndian

    let htons  = isLittleEndian ? _OSSwapInt16 : { $0 }
    let htonl  = isLittleEndian ? _OSSwapInt32 : { $0 }
    let htonll = isLittleEndian ? _OSSwapInt64 : { $0 }
    let ntohs  = isLittleEndian ? _OSSwapInt16 : { $0 }
    let ntohl  = isLittleEndian ? _OSSwapInt32 : { $0 }
    let ntohll = isLittleEndian ? _OSSwapInt64 : { $0 }

Use Swifty JSON (or any other serializer)

In many projects, I use SwiftyJSON to read and write JSON, and I thought how to use it conveniently with this framework, and here is how I see the thing :
in HttpResponseBody, instead of serialize inside the switch self, have a generic Serializer protocol to provide a String? with just a method to serialize. in the switch self, we call the appropriate Serializer, and that way, we can extend the serializers we want and override :)
How does it feels ? if you're ok, I do it tomorrow morning

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)'

Asynchronous handlers

Hi, we're planning to use your server instead of GCDWebServer, but we need to asynchronously handle requests. This means that, when specifying a request handler, we don't want to immediately return a HttpResponse but be able to pass this to some kind of completion handler.
Do you think this could be a welcome improvement to the swifter project? Also, would you be able to do it?

Thanks!

Socket server support

I tried running the socket instance, it doesn't work. Can you provide an example ?

type of expression is ambiguous without more context

Hi

I get the error "type of expression is ambiguous without more context" when I use .Html() this way:
server["/hello"] = { .OK(.Html("You asked for ")) }

why does the following work and mine not?
server["/hello"] = { .OK(.Html("You asked for " + $0.path)) }
Thanks

Close and reopen sockets on suspend-resume?

Hi. I'm not 100% sure this is what's happening, but it seems that the server sockets are getting closed after the app is suspended a while, and not re-opened. Is it possible for swifter to handle that?

I guess I could handle it, too, killing the server on suspend and re-creating it on resume. Anyway, FYI.

Dependency "swifter" has no shared framework schemes

I didn't find following issue in this project:

On "carthage update" i got following error:

Dependency "swifter" has no shared framework schemes

I have created clean macos applicattion(cocoa).
Here is my config:

$ cat Cartfile
github "glock45/swifter"

$ carthage update
*** Fetching swifter
*** Checking out swifter at "1.0.2"
*** xcodebuild output can be found in /var/folders/ss/xffzdh1s75sdvv_y2z4q_4l40000gn/T/carthage-xcodebuild.LZbQeX.log
*** Skipped building swifter due to the error:
Dependency "swifter" has no shared framework schemes

If you believe this to be an error, please file an issue with the maintainers at >https://github.com/glock45/swifter/issues/new

$ cat /var/folders/ss/xffzdh1s75sdvv_y2z4q_4l40000gn/T/carthage-xcodebuild.LZbQeX.log

^^^^^^^ empty

string? not unwrapped

In String+Misc.swift:44:20 the

return String(..., encoding: NSUT8StringEncoding)

needs to be unwrapped. A nil coalescing operator should work here.

HttpRequest.MultiPart missing member 'name' and 'fileName' (when using Carthage)

I included Swifter 1.0.6 in my project using Carthage and then simply copied the server.POST["/upload"] block from demoServer.swift, but the line:

response += "Name: \(multipart.name) File name: \(multipart.fileName) Size: \(multipart.body.count)<br>" does not build. I get unresolved identifier, "value of type 'HttpRequests.MultiPart' has no member 'fileName' " (and the same for .name).

Note that if I download the full source from GitHub, everything builds and runs just fine - the issue is only when I use Carthage to include Swifter in my project. Lastly, I am new to both Xcode & swift, so if I am missing something stupid, please let me know what...

Write to a stream vs String

Wouldn't it be better for handlers to be writing to a stream instead of to a string? Could be better for large files and if you ever want to handle multiple handlers for one request.

Linux support?

Do we plan to support Linux with latest open sourced tool-chain?

Swifter does not work on iOS Device in Background

Swifter does not start its server in a UIBackgroundTask
That is the reason why the Swifter Demo App does not work on a real iOS Device but in iOS Simulator. It's very important to start the server in a Background Task. Otherwise the app wont answer for Example to the request when you access your webpage from MobileSafari!

Carthage support

carthage update --platform Mac
*** Cloning swifter
*** Checking out swifter at "1.0.2"
*** xcodebuild output can be found in /var/folders/jk/7d8wk5b17gq7l4j908167kbr0000gn/T/carthage-xcodebuild.JhajtD.log
Dependency "swifter" has no shared framework schemes

If you believe this to be an error, please file an issue with the maintainers at https://github.com/glock45/swifter/issues/new

I am going to submit a PR for this issue.

Noob guide

For the benefit of people who have never used Swift yet, and perhaps haven't touched XCode since 2008, could you perhaps add a simple getting started guide to creating a simple web app and running it locally to serve traffic?

And/or perhaps link to some web apps built with Swifter. Github searches for "swifter" include matches for "swift"; so I didn't find any so far.

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

Wrap up a new version

Latest version is 1.0.2 from October, maybe it's time for a 1.1 including all latest changes if they are stable enough?
I don't want to point directly to master or a specific commit, instead I'd prefer to point to the last stable release

Why Socket is it all Static ?

Socket is a Struct never really used, just by its static method.
We see the socket : CInt as parameter nearly each time,
but why not use a class, with tcpForListen as init, socketIdentifier Cint as property and avoiding socket parameter and use the class paradigm ??

Sending an image with Swifter

This is more of a newbie question than an issue. How would I go about sending an image file or other binary from Swifter? I haven't been able to find an example of how to do this. Any help would be appreciated.

Serve images?

Really nice project! But will it be possible to use this to serve other file types than text? Image support would make this fantastic.

Conflict between two routes

If I add a route after adding "/" route, it always redirect with "/" because it matches first.
I try to handle this, just to warn you :)

print(statusTokens)

There's a print(statusTokens) on line 23 of HttpParser.swift
It's kinda cluttering my debugging output.

I'm not sure if I should remove it or if you should, as I don't want to edit my pod-frameworks.

Use blue folder containing html files

Hi,

This is not an issue, but I just wanted to let you know that I'm adding complete folders to my Bundle (by adding them as folder, not as group) and then using this code to access them:

server["/public/(.+)"] = directory("HTML/")

func directory(dir: String) -> ( HttpRequest -> HttpResponse ) {
    return { request in
        if let localPath = request.capturedUrlGroups.first {
            print(localPath)
            if let filesPath = NSBundle.mainBundle().pathForResource(dir + localPath, ofType: "") {
                print(filesPath)
                if let fileBody = NSData(contentsOfFile: filesPath) {
                    return HttpResponse.RAW(200, "OK", nil, fileBody)
                }
            }
        }
        return HttpResponse.NotFound
    }
}

Where HTML/ is the blue folder added to my iOS project.

So by going to http://url-to-iphone:port/public/index.html i'm accessing index.html inside the HTML/-folder

Byte range requests for video?

Any chance that Swifter will support byte range requests, so that video can be played back in mobile safari for example?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.