Giter Site home page Giter Site logo

royccat / perfect Goto Github PK

View Code? Open in Web Editor NEW

This project forked from perfectlysoft/perfect

0.0 2.0 0.0 52.04 MB

Server-side Swift. The Perfect library, application server, connectors and example apps. (For mobile back-end development, website and web app development, and more...)

Home Page: https://www.perfect.org

License: Apache License 2.0

Swift 100.00%

perfect's Introduction

Perfect: Server-Side Swift

Perfect logo

Swift 3.0 Platforms OS X | Linux License Apache Docs GitHub issues codebeat Twitter Join the chat at https://gitter.im/PerfectlySoft/Perfect

2016-07-07 NOTE: We have moved the core HTTP, HTTPServer and Mustache code into their own repositories. This introduces compilation issues with existing code and you will need to import one or more of the following packages, depending on your usage:

import PerfectMustache
import PerfectHTTP
import PerfectHTTPServer

You will also need to adjust your Package.swift file. You should only need to change the Perfect dependency to the following:

https://github.com/PerfectlySoft/Perfect-HTTPServer.git

--

The master branch of this project currently compiles with the default Swift 3.0 toolchain included in Xcode 8 beta 2. On Ubuntu use the Swift 3.0 Preview 2 toolchain, released July 7th.

Important: On OS X you must set the Xcode command line tools preference as follows: Xcode Prefs

If you do not do this you will experience compile time errors when using SPM on the command line.

If you are still having build problems with any of the code in our repositories, try doing a clean build with Swift Package Manager by typing:

swift build --clean=dist ; swift build

--

Perfect is an application server for Linux or OS X which provides a framework for developing web and other REST services in the Swift programming language. Its primary focus is on facilitating mobile apps which require backend server software, enabling you to use one language for both front and back ends.

Perfect operates using either its own stand-alone HTTP/HTTPS server or through FastCGI. It provides a system for loading your own Swift based modules at startup and for interfacing those modules with its request/response objects or to the built-in mustache template processing system.

Perfect is built on its own high performance completely asynchronous networking engine with the goal of providing a scalable option for internet services. It supports SSL out of the box and provides a suite of tools which are commonly required by internet servers, such as WebSockets and iOS push notifications, but does not limit your options. Feel free to swap in your own favorite JSON or templating systems, etc.

Quick Start

Swift 3.0

Ensure you have properly installed a Swift 3.0 toolchain from Swift.org. In the terminal, typing:

swift --version

should produce something like the following:

Apple Swift version 3.0 (swiftlang-800.0.33.1 clang-800.0.31)
Target: x86_64-apple-macosx10.9

OS X

Perfect relies on Home Brew for installing dependencies on OS X. This is currently limited to OpenSSL. To install Home Brew, in the Terminal, type:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

To install OpenSSL:

brew install openssl
brew link openssl --force

Linux

Perfect relies on OpenSSL, libssl-dev and uuid:

sudo apt-get install openssl libssl-dev uuid-dev

Build Starter Project

The following will clone and build an empty starter project and launch the server on port 8181.

git clone https://github.com/PerfectlySoft/PerfectTemplate.git
cd PerfectTemplate
swift build
.build/debug/PerfectTemplate

You should see the following output:

Starting HTTP server on 0.0.0.0:8181 with document root ./webroot

This means the server is running and waiting for connections. Access http://localhost:8181/ to see the greeting. Hit control-c to terminate the server.

You can view the full source code for PerfectTemplate.

Xcode

Swift Package Manager can generate an Xcode project which can run the PerfectTemplate server and provide full source code editing and debugging for your project. Enter the following in your terminal:

swift package generate-xcodeproj

Open the generated file "PerfectTemplate.xcodeproj". Ensure that you have selected the executable target and selected it to run on "My Mac". You can now run and debug the server.

Next Steps

These example snippets show how to accomplish several common tasks that one might need to do when developing a Web/REST application. In all cases, the request and response variables refer, respectively, to the HTTPRequest and HTTPResponse objects which are given to your URL handlers.

Consult the API reference for more details.

Get a client request header

if let acceptEncoding = request.header(.acceptEncoding) {
	...
}

Get client GET or POST parameters

if let foo = request.param(name: "foo") {
	...
}   
if let foo = request.param(name: "foo", defaultValue: "default foo") {
	...
}
let foos: [String] = request.params(named: "foo")

Get the current request path

let path = request.path

Access the server's document directory and return an image file to the client

let docRoot = request.documentRoot
do {
    let mrPebbles = File("\(docRoot)/mr_pebbles.jpg")
    let imageSize = mrPebbles.size
    let imageBytes = try mrPebbles.readSomeBytes(count: imageSize)
    response.setHeader(.contentType, value: MimeType.forExtension("jpg"))
    response.setHeader(.contentLength, value: "\(imageBytes.count)")
    response.setBody(bytes: imageBytes)
} catch {
    response.status = .internalServerError
    response.setBody(string: "Error handling request: \(error)")
}
response.completed()

Get client cookies

for (cookieName, cookieValue) in request.cookies {
	...
}

Set client cookie

let cookie = HTTPCookie(name: "cookie-name", value: "the value", domain: nil,
                    expires: .session, path: "/",
                    secure: false, httpOnly: false)
response.addCookie(cookie)

Return JSON data to client

response.setHeader(.contentType, value: "application/json")
let d: [String:Any] = ["a":1, "b":0.1, "c": true, "d":[2, 4, 5, 7, 8]]
    
do {
    try response.setBody(json: d)
} catch {
    //...
}
response.completed()

This snippet uses the built-in JSON encoding. Feel free to bring in your own favorite JSON encoder/decoder.

Redirect the client

response.status = .movedPermanently
response.setHeader(.location, value: "http://www.perfect.org/")
response.completed()

Filter and handle 404 errors in a custom manner

struct Filter404: HTTPResponseFilter {
	func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
		callback(.continue)
	}
	
	func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
		if case .notFound = response.status {
			response.bodyBytes.removeAll()
			response.setBody(string: "The file \(response.request.path) was not found.")
			response.setHeader(.contentLength, value: "\(response.bodyBytes.count)")
			callback(.done)
		} else {
			callback(.continue)
		}
	}
}

let server = HTTPServer()
server.setResponseFilters([(Filter404(), .high)])
server.serverPort = 8181
try server.start()

Repository Layout

We have finished refactoring Perfect to support Swift Package Manager. The Perfect project has been split up into the following repositories:

  • Perfect - This repository contains the core PerfectLib and will continue to be the main landing point for the project.
  • PerfectTemplate - A simple starter project which compiles with SPM into a stand-alone executable HTTP server. This repository is ideal for starting on your own Perfect based project.
  • PerfectDocs - Contains all API reference related material.
  • PerfectExamples - All the Perfect example projects and documentation.
  • Perfect-Mustache - Mustache template processor.
  • Perfect-Notifications - iOS Notifications (APNS) Support.
  • PerfectTemplateFCGI - A simple starter project which compiles with SPM into a FastCGI server suitable for use with Apache 2.4 or NGINX. This repository is ideal for starting on your own Perfect based project if you are required to use an existing server which supports FastCGI.
  • Perfect-Redis - Redis database connector.
  • Perfect-SQLite - SQLite3 database connector.
  • Perfect-PostgreSQL - PostgreSQL database connector.
  • Perfect-MySQL - MySQL database connector.
  • Perfect-MongoDB - MongoDB database connector.
  • Perfect-FastCGI-Apache2.4 - Apache 2.4 FastCGI module; required for the Perfect FastCGI server variant.

The database connectors are all stand-alone and can be used outside of the Perfect framework and server.

Further Information

For more information on the Perfect project, please visit perfect.org.

perfect's People

Contributors

kjessup avatar seanstephens avatar groovelab avatar califrench avatar ludagoo avatar petrpavlik avatar coderxpert avatar chris-sean avatar wuqiong avatar taplin avatar theabstractdev avatar rymcol avatar johnlinvc avatar kingiol avatar jezhawk avatar dabeck avatar tspoonman avatar gitter-badger avatar shaneqi avatar mikehenson avatar mcritz avatar maryom avatar jordonedavidson avatar iamjono avatar joeferrucci avatar solidsnack avatar clivemoore avatar c0deh4cker avatar s2ler avatar

Watchers

James Cloos avatar  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.