The scenario would be app host a GCDWebServer, and when it receives an API Request like a "GET" HTTP request - http://serverURL:8080/search/brand?query=benz&page=1
. Then return the response with a JSON format data to the sender.
I think I should use GCDWebServerDataResponse(jsonObject: contentType:)
.
However, I get two questions:
How should I construct the json file for response data. Should I create it in swift manually or just save a json file in the project. What is the generic or correct way to configure the json data in GCDWebServer?
My request includes a query string("query=benz"), how to detect it by using
webServer.addHandler
. In my case, I need to return the different filtered data according to search query string.
func initWebServer() {
let path = "/search/brand"
webServer.addHandler(forMethod: "GET", path: path, request: GCDWebServerRequest.self, processBlock: { request in
print("Search request detected")
return GCDWebServerDataResponse(jsonObject: <#T##Any#>, contentType: <#T##String#>)
})
webServer.start(withPort: 8080, bonjourName: "My Test Site")
DispatchQueue.main.async {
if let serverURL = self.webServer.serverURL {
print("VISIT \(serverURL) in your web browser")
} else {
print("Not connected!")
}
}
}
After some research & test by myself, I found I could get the query
& page
parameters from GCDWebServer handler's request.
As below code showed, I'm not sure if it is appropriate in real product environment. But it is fully worked per my test.
import SwiftUI
import GCDWebServer
class GCDServer {
lazy var webServer = GCDWebServer()
static var serverURL: URL!
func initWebServer() {
let path = "/search/brand"
webServer.addHandler(forMethod: "GET", path: path, request: GCDWebServerRequest.self, processBlock: { request in
print("WebServer - GET detected")
if let query = request.query {
if query["query"]?.lowercased() == "Nike" {
if let page = query["page"], Int(page)! <= 3 {
return GCDWebServerDataResponse(jsonObject: JsonLoader().jsonStrToDict(forName: "mock-data-page\(page)") ?? [])
} else {
print("Page num cross the limit of 3.")
return nil
}
} else {
print("keyword is not matched!")
return nil
}
}
return nil
})
// Binding server to localhost
do {
try webServer.start(options: ["Port": 8080, "BindToLocalhost": true])
} catch {
print(error)
}
DispatchQueue.main.async {
if let serverURL = self.webServer.serverURL {
GCDServer.serverURL = serverURL
print("VISIT \(serverURL) in your web browser")
} else {
print("Not connected with network!")
}
}
}
func stopWebServer() {
webServer.stop()
}
}