0

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:

  1. 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?

  2. 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()
    }
}
jelhan
  • 6,149
  • 1
  • 19
  • 35
Zhou Haibo
  • 1,681
  • 1
  • 12
  • 32
  • Are you planing to implement a REST API that is following [JSON:API specification](https://jsonapi.org/)? It's not that clear to me from your question but you have added that tag. – jelhan Jul 01 '20 at 19:24
  • @jelhan, I wanted to use GCDWebServer to return some JSON object, but I didn't know how to return different contents according to http request's `query` and `page number`. I have found the solution, see my updates in question. – Zhou Haibo Jul 03 '20 at 07:45
  • What is your solution? – Wang Liang Jul 16 '21 at 19:42
  • @MERN, well it has been a long time, but I think I have updated it at that time. So `see my updates in question`. – Zhou Haibo Jul 19 '21 at 03:15

0 Answers0