httpswift / swifter Goto Github PK
View Code? Open in Web Editor NEWTiny http server engine written in Swift programming language.
License: BSD 3-Clause "New" or "Revised" License
Tiny http server engine written in Swift programming language.
License: BSD 3-Clause "New" or "Revised" License
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!
It would be cool if using the .JSON
, et al. response mechanism, it automatically set the response Content-Type header appropriately.
Thanks!
Hey,
I noticed a podspec file in the repo.
Is there any plan on publishing swifter as a pod ?
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
this is my code
let server = HttpServer()
server["/(.+)"] = HttpHandlers.directory(NSBundle.mainBundle().resourcePath! + "/www")
server.start(80, error: nil)
self.server = server
Q: I want to visit index.html with http://192.168.0.1 not http://192.168.0.1/index.html,
what should I do? thx!!!
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 }
Really nice project! But will it be possible to use this to serve other file types than text? Image support would make this fantastic.
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!
I tried running the socket instance, it doesn't work. Can you provide an example ?
Now that Linux has Swift and GCD... any chance of porting this? https://swift.org
Any chance that Swifter will support byte range requests, so that video can be played back in mobile safari for example?
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 :)
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.
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.
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
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
Is it supported? Or will be?
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?
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
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.
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 ??
Hi, it would be cool if you can add cocoapods ( http://cocoapods.org ) support to your project!
In String+Misc.swift:44:20
the
return String(..., encoding: NSUT8StringEncoding)
needs to be unwrapped. A nil coalescing operator should work here.
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.
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!
[!] Unable to satisfy the following requirements:
- `Swifter (~> 1.0.3)` required by `Podfile`
'pod install' with above error.
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)'
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.
Replace line 34 with following:
response += (files.map { "<tr><td><a href=\"\(request.url)/\($0)\">\($0)</a></td></tr>"}).joinWithSeparator("")
This will fix the compilation error.
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.
I upload a text file from the app to /files(.+), and the response I got is NOT FOUND(404)
What should I do at the server-side to get the 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
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.
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
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;
}
How does one set the response headers?
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 schemesIf 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
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...
How to use POST method, does swifter support it?
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!
According to cocoapods.org Swifter is still 1.0.6! Can this be updated?
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
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?
Do we plan to support Linux with latest open sourced tool-chain?
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.
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?
Could you tag a new release with the Package.swift file?
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?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.