Giter Site home page Giter Site logo

chrischares / blackfish Goto Github PK

View Code? Open in Web Editor NEW

This project forked from elliottminns/blackfire

0.0 1.0 0.0 128 KB

A fast HTTP web server based on Node.js and Express written in Swift

License: Apache License 2.0

Swift 99.15% Objective-C 0.85%

blackfish's Introduction

Blackfish

A Node/Express Inspired Web Framework for Swift that works on iOS, OS X, and Ubuntu.

Travis Badge

  • Insanely fast
  • Single Threaded
  • Beautiful syntax
  • Type safe

Getting Started

You must have Swift 2.2 or later installed. You can learn more about Swift 2.2 at Swift.org

Work in Progress

This is a work in progress and will likely change frequently, pull requests are welcome!

Server

Starting the server is as simple as express.

main.swift

import Blackfish

let app = Blackfish()

app.get("/") { request, response in
    response.send(text: "Hello World!")
}

app.listen(port: 3000) { error in
    if error == nil {
        print("Example app listening on port 3000")
    }
}

If you are having trouble connecting, make sure your ports are open. Check out apt-get ufw for simple port management.

Routing

Routing in Blackfish is simple and very similar to Express.

main.swift

app.get("/welcome") { request, response in
	response.send(text: "Hello")
}

app.post('/') { request, response in
    response.send(text: 'Got a POST request')
});

//...start server

Router

You can also create a Router object which will allow you to define multiple routes with a prefix.

let router = Router()

router.get("/") { request, response in
    response.send(text: "Bird is the word")
}

router.get("/about") { request, response in
    response.send(text: "Don't you know, about the bird?")
}

app.use(path: "/birds", router: router)

// ...start server

Navigating to http://example.com/birds will show a page with Bird is the word and navigating to http://example.com/birds/about will show a page with "Don't you know, about the bird?".

JSON

Responding with JSON is easy.

app.get("version") { request, response in
	response.send(json: ["version": "1.0"])
}

This responds to all requests to http://example.com/version with the JSON dictionary {"version": "1.0"} and Content-Type: application/json.

Views

You can also respond with HTML pages.

app.get("/") { request, response in
    response.render("index.html") 
}

Just put the file in the Resources folder at the root of your project and it will be served.

Response

A manual response can be returned if you want to set something like cookies.

Route.get("cookie") { request, response in
    response.status = .OK
    response.text = "Cookie was set"
	response.cookies["test"] = "123"
	response.send()
}

The Status enum above (.OK) can be one of the following.

public enum Status {
    case OK, Created, Accepted
    case MovedPermanently
    case BadRequest, Unauthorized, Forbidden, NotFound
    case ServerError
    case Unknown
    case Custom(Int)
}

Or something custom.

let status: Status = .Custom(420) //https://dev.twitter.com/overview/api/response-codes

Public

All files put in the Public folder at the root of your project will be available at the root of your domain. This is a great place to put your assets (.css, .js, .png, etc).

Request

Every route call gets passed a Request object. This can be used to grab query and path parameters.

This is a list of the properties available on the request object.

let method: Method
var parameters: [String: String] //URL parameters like id in user/:id
var data: [String: String] //GET or POST data
var cookies: [String: String]
var session: Session

Middleware

Similar to Express, Blackfish provides Middleware which can be used to extend the request stack.

Below is an example of a validation Middleware, that validates every request before passing it down the stack.

let validator = Middleware { (request, response, next) in
    
    // Some validation logic
    if validator.validate(request) {

        // Go to the next call in the stack.
        next()

    } else {

        // Return an error and don't call anything else in the stack.
        response.send(error: "Request was unauthorized")
    }
}

You can also use middleware on a path which will add it to that path and further on.

let userDetail = Middleware(path: "/user") { (request, response, next) in {
    let user = findUserById(request.data["userId"])
    request.data["user"] = user
    next()
}

Using Middleware can allow you endless possibilities with a simple interface.

Session

Sessions will be kept track of using the blackfish-session cookie. The default (and currently only) session driver is .Memory.

if let name = request.session.data["name"] {
	//name was in session	
}

//store name in session
request.session.data["name"] = "Blackfish"

Deploying

Vapor has been successfully tested on Ubuntu 14.04 LTS (DigitalOcean) and Ubuntu 15.10 (VirtualBox).

To deploy to DigitalOcean, simply

  • Install Swift 2.2
    • wget the .tar.gz from Apple
    • Set the export PATH in your ~/.bashrc
    • (you may need to install binutils as well if you see ar not found)
  • Set Blackfish as a dependency of your project in your Package.swift
    dependencies:[
        // ...Previous dependencies
        .Package(url: "https://github.com/elliottminns/blackfish", majorVersion: 0)
    ]
  • cd into the repository
    • Run swift build
    • Run .build/debug/MyApp
    • (you may need to run as sudo to use certain ports)
    • (you may need to install ufw to set appropriate ports)

Attributions

This project is based on Vapor by Tanner Nelson. It uses compatibilty code from NSLinux by johnno1962.

Go checkout and star their repos.

blackfish's People

Contributors

elliottminns avatar kimar avatar konnork avatar

Watchers

 avatar

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.