-
Notifications
You must be signed in to change notification settings - Fork 554
Expand file tree
/
Copy pathHttpServer.swift
More file actions
84 lines (70 loc) · 2.68 KB
/
HttpServer.swift
File metadata and controls
84 lines (70 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//
// HttpServer.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
open class HttpServer: HttpServerIO {
public static let VERSION: String = {
#if os(Linux)
return "1.5.0"
#else
let bundle = Bundle(for: HttpServer.self)
guard let version = bundle.infoDictionary?["CFBundleShortVersionString"] as? String else { return "Unspecified" }
return version
#endif
}()
private let router = HttpRouter()
public override init() {
self.DELETE = MethodRoute(method: "DELETE", router: router)
self.PATCH = MethodRoute(method: "PATCH", router: router)
self.HEAD = MethodRoute(method: "HEAD", router: router)
self.POST = MethodRoute(method: "POST", router: router)
self.GET = MethodRoute(method: "GET", router: router)
self.PUT = MethodRoute(method: "PUT", router: router)
self.delete = MethodRoute(method: "DELETE", router: router)
self.patch = MethodRoute(method: "PATCH", router: router)
self.head = MethodRoute(method: "HEAD", router: router)
self.post = MethodRoute(method: "POST", router: router)
self.get = MethodRoute(method: "GET", router: router)
self.put = MethodRoute(method: "PUT", router: router)
}
public var DELETE, PATCH, HEAD, POST, GET, PUT: MethodRoute
public var delete, patch, head, post, get, put: MethodRoute
public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? {
get { return nil }
set {
router.register(nil, path: path, handler: newValue)
}
}
public var routes: [String] {
return router.routes()
}
public var notFoundHandler: ((HttpRequest) -> HttpResponse)?
public var middleware = [(HttpRequest) -> HttpResponse?]()
override open func dispatch(_ request: HttpRequest) -> ([String: String], (HttpRequest) -> HttpResponse) {
for layer in middleware {
if let response = layer(request) {
return ([:], { _ in response })
}
}
if let result = router.route(request.method, path: request.path) {
return result
}
if let notFoundHandler = self.notFoundHandler {
return ([:], notFoundHandler)
}
return super.dispatch(request)
}
public struct MethodRoute {
public let method: String
public let router: HttpRouter
public subscript(path: String) -> ((HttpRequest) -> HttpResponse)? {
get { return nil }
set {
router.register(method, path: path, handler: newValue)
}
}
}
}