{"id":16948617,"url":"https://github.com/timoliver/webserverkit","last_synced_at":"2025-06-11T18:33:47.813Z","repository":{"id":158287170,"uuid":"633913149","full_name":"TimOliver/WebServerKit","owner":"TimOliver","description":"A fork of the #1 HTTP server for iOS, macOS \u0026 tvOS","archived":false,"fork":false,"pushed_at":"2023-11-27T15:45:33.000Z","size":12456,"stargazers_count":6,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-05-12T02:18:02.075Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Objective-C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/TimOliver.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-04-28T15:10:35.000Z","updated_at":"2025-02-01T04:07:02.000Z","dependencies_parsed_at":"2023-11-27T16:49:47.800Z","dependency_job_id":"30c2c844-3f77-4c93-bb2d-07e2cb12fc8f","html_url":"https://github.com/TimOliver/WebServerKit","commit_stats":null,"previous_names":[],"tags_count":44,"template":false,"template_full_name":null,"purl":"pkg:github/TimOliver/WebServerKit","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TimOliver%2FWebServerKit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TimOliver%2FWebServerKit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TimOliver%2FWebServerKit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TimOliver%2FWebServerKit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/TimOliver","download_url":"https://codeload.github.com/TimOliver/WebServerKit/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TimOliver%2FWebServerKit/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259316739,"owners_count":22839529,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-13T21:51:40.089Z","updated_at":"2025-06-11T18:33:47.751Z","avatar_url":"https://github.com/TimOliver.png","language":"Objective-C","funding_links":[],"categories":[],"sub_categories":[],"readme":"___In January 2023, [GCDWebServer](https://github.com/swisspol/GCDWebServer) was archived by its author. Since I was planning to eventually use this library in my own side projects, I've decided to fork GCDWebServer and continue development of it under a new name. I plan to slowly add updates to this repo as I get the time. -Tim___\n\nOverview\n========\n\n[![Build Status](https://travis-ci.org/swisspol/GCDWebServer.svg?branch=master)](https://travis-ci.org/swisspol/GCDWebServer)\n[![Version](http://cocoapod-badges.herokuapp.com/v/GCDWebServer/badge.png)](https://cocoapods.org/pods/GCDWebServer)\n[![Platform](http://cocoapod-badges.herokuapp.com/p/GCDWebServer/badge.png)](https://github.com/swisspol/GCDWebServer)\n[![License](http://img.shields.io/cocoapods/l/GCDWebServer.svg)](LICENSE)\n\nGCDWebServer is a modern and lightweight GCD based HTTP 1.1 server designed to be embedded in iOS, macOS \u0026 tvOS apps. It was written from scratch with the following goals in mind:\n* Elegant and easy to use architecture with only 4 core classes: server, connection, request and response (see \"Understanding GCDWebServer's Architecture\" below)\n* Well designed API with fully documented headers for easy integration and customization\n* Entirely built with an event-driven design using [Grand Central Dispatch](http://en.wikipedia.org/wiki/Grand_Central_Dispatch) for best performance and concurrency\n* No dependencies on third-party source code\n* Available under a friendly [New BSD License](LICENSE)\n\nExtra built-in features:\n* Allow implementation of fully asynchronous handlers of incoming HTTP requests\n* Minimize memory usage with disk streaming of large HTTP request or response bodies\n* Parser for [web forms](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4) submitted using \"application/x-www-form-urlencoded\" or \"multipart/form-data\" encodings (including file uploads)\n* [JSON](http://www.json.org/) parsing and serialization for request and response HTTP bodies\n* [Chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding) for request and response HTTP bodies\n* [HTTP compression](https://en.wikipedia.org/wiki/HTTP_compression) with gzip for request and response HTTP bodies\n* [HTTP range](https://en.wikipedia.org/wiki/Byte_serving) support for requests of local files\n* [Basic](https://en.wikipedia.org/wiki/Basic_access_authentication) and [Digest Access](https://en.wikipedia.org/wiki/Digest_access_authentication) authentications for password protection\n* Automatically handle transitions between foreground, background and suspended modes in iOS apps\n* Full support for both IPv4 and IPv6\n* NAT port mapping (IPv4 only)\n\nIncluded extensions:\n* [GCDWebUploader](GCDWebUploader/GCDWebUploader.h): subclass of ```GCDWebServer``` that implements an interface for uploading and downloading files using a web browser\n* [GCDWebDAVServer](GCDWebDAVServer/GCDWebDAVServer.h): subclass of ```GCDWebServer``` that implements a class 1 [WebDAV](https://en.wikipedia.org/wiki/WebDAV) server (with partial class 2 support for macOS Finder)\n\nWhat's not supported (but not really required from an embedded HTTP server):\n* Keep-alive connections\n* HTTPS\n\nRequirements:\n* macOS 10.7 or later (x86_64)\n* iOS 8.0 or later (armv7, armv7s or arm64)\n* tvOS 9.0 or later (arm64)\n* ARC memory management only (if you need MRC support use GCDWebServer 3.1 or earlier)\n\nGetting Started\n===============\n\nDownload or check out the [latest release](https://github.com/swisspol/GCDWebServer/releases) of GCDWebServer then add the entire \"GCDWebServer\" subfolder to your Xcode project. If you intend to use one of the extensions like GCDWebDAVServer or GCDWebUploader, add these subfolders as well. Finally link to `libz` (via Target \u003e Build Phases \u003e Link Binary With Libraries) and add `$(SDKROOT)/usr/include/libxml2` to your header search paths (via Target \u003e Build Settings \u003e HEADER_SEARCH_PATHS).\n\nAlternatively, you can install GCDWebServer using [CocoaPods](http://cocoapods.org/) by simply adding this line to your Podfile:\n```\npod \"GCDWebServer\", \"~\u003e 3.0\"\n```\nIf you want to use GCDWebUploader, use this line instead:\n```\npod \"GCDWebServer/WebUploader\", \"~\u003e 3.0\"\n```\nOr this line for GCDWebDAVServer:\n```\npod \"GCDWebServer/WebDAV\", \"~\u003e 3.0\"\n```\n\nAnd finally run `$ pod install`.\n\nYou can also use [Carthage](https://github.com/Carthage/Carthage) by adding this line to your Cartfile (3.2.5 is the first release with Carthage support):\n```\ngithub \"swisspol/GCDWebServer\" ~\u003e 3.2.5\n```\n\nThen run `$ carthage update` and add the generated frameworks to your Xcode projects (see [Carthage instructions](https://github.com/Carthage/Carthage#adding-frameworks-to-an-application)).\n\nHelp \u0026 Support\n==============\n\nFor help with using GCDWebServer, it's best to ask your question on Stack Overflow with the [`gcdwebserver`](http://stackoverflow.com/questions/tagged/gcdwebserver) tag. For bug reports and enhancement requests you can use [issues](https://github.com/swisspol/GCDWebServer/issues) in this project.\n\nBe sure to read this entire README first though!\n\nHello World\n===========\n\nThese code snippets show how to implement a custom HTTP server that runs on port 8080 and returns a \"Hello World\" HTML page to any request. Since GCDWebServer uses GCD blocks to handle requests, no subclassing or delegates are needed, which results in very clean code.\n\n**IMPORTANT:** If not using CocoaPods, be sure to add the `libz` shared system library to the Xcode target for your app.\n\n**macOS version (command line tool):**\n```objectivec\n#import \"GCDWebServer.h\"\n#import \"GCDWebServerDataResponse.h\"\n\nint main(int argc, const char* argv[]) {\n  @autoreleasepool {\n    \n    // Create server\n    GCDWebServer* webServer = [[GCDWebServer alloc] init];\n    \n    // Add a handler to respond to GET requests on any URL\n    [webServer addDefaultHandlerForMethod:@\"GET\"\n                             requestClass:[GCDWebServerRequest class]\n                             processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {\n      \n      return [GCDWebServerDataResponse responseWithHTML:@\"\u003chtml\u003e\u003cbody\u003e\u003cp\u003eHello World\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e\"];\n      \n    }];\n    \n    // Use convenience method that runs server on port 8080\n    // until SIGINT (Ctrl-C in Terminal) or SIGTERM is received\n    [webServer runWithPort:8080 bonjourName:nil];\n    NSLog(@\"Visit %@ in your web browser\", webServer.serverURL);\n    \n  }\n  return 0;\n}\n```\n\n**iOS version:**\n```objectivec\n#import \"GCDWebServer.h\"\n#import \"GCDWebServerDataResponse.h\"\n\n@interface AppDelegate : NSObject \u003cUIApplicationDelegate\u003e {\n  GCDWebServer* _webServer;\n}\n@end\n\n@implementation AppDelegate\n\n- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {\n  \n  // Create server\n  _webServer = [[GCDWebServer alloc] init];\n  \n  // Add a handler to respond to GET requests on any URL\n  [_webServer addDefaultHandlerForMethod:@\"GET\"\n                            requestClass:[GCDWebServerRequest class]\n                            processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {\n    \n    return [GCDWebServerDataResponse responseWithHTML:@\"\u003chtml\u003e\u003cbody\u003e\u003cp\u003eHello World\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e\"];\n    \n  }];\n  \n  // Start server on port 8080\n  [_webServer startWithPort:8080 bonjourName:nil];\n  NSLog(@\"Visit %@ in your web browser\", _webServer.serverURL);\n  \n  return YES;\n}\n\n@end\n```\n\n**macOS Swift version (command line tool):**\n\n***webServer.swift***\n```swift\nimport Foundation\nimport GCDWebServer\n\nfunc initWebServer() {\n\n    let webServer = GCDWebServer()\n\n    webServer.addDefaultHandler(forMethod: \"GET\", request: GCDWebServerRequest.self, processBlock: {request in\n            return GCDWebServerDataResponse(html:\"\u003chtml\u003e\u003cbody\u003e\u003cp\u003eHello World\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e\")\n            \n        })\n        \n    webServer.start(withPort: 8080, bonjourName: \"GCD Web Server\")\n    \n    print(\"Visit \\(webServer.serverURL) in your web browser\")\n}\n```\n\n***WebServer-Bridging-Header.h***\n```objectivec\n#import \u003cGCDWebServer/GCDWebServer.h\u003e\n#import \u003cGCDWebServer/GCDWebServerDataResponse.h\u003e\n```\n\nWeb Based Uploads in iOS Apps\n=============================\n\nGCDWebUploader is a subclass of ```GCDWebServer``` that provides a ready-to-use HTML 5 file uploader \u0026 downloader. This lets users upload, download, delete files and create directories from a directory inside your iOS app's sandbox using a clean user interface in their web browser.\n\nSimply instantiate and run a ```GCDWebUploader``` instance then visit ```http://{YOUR-IOS-DEVICE-IP-ADDRESS}/``` from your web browser:\n\n```objectivec\n#import \"GCDWebUploader.h\"\n\n@interface AppDelegate : NSObject \u003cUIApplicationDelegate\u003e {\n  GCDWebUploader* _webUploader;\n}\n@end\n\n@implementation AppDelegate\n\n- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {\n  NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];\n  _webUploader = [[GCDWebUploader alloc] initWithUploadDirectory:documentsPath];\n  [_webUploader start];\n  NSLog(@\"Visit %@ in your web browser\", _webUploader.serverURL);\n  return YES;\n}\n\n@end\n```\n\nWebDAV Server in iOS Apps\n=========================\n\nGCDWebDAVServer is a subclass of ```GCDWebServer``` that provides a class 1 compliant [WebDAV](https://en.wikipedia.org/wiki/WebDAV) server. This lets users upload, download, delete files and create directories from a directory inside your iOS app's sandbox using any WebDAV client like [Transmit](https://panic.com/transmit/) (Mac), [ForkLift](http://binarynights.com/forklift/) (Mac) or [CyberDuck](http://cyberduck.io/) (Mac / Windows).\n\nGCDWebDAVServer should also work with the [macOS Finder](http://support.apple.com/kb/PH13859) as it is partially class 2 compliant (but only when the client is the macOS WebDAV implementation).\n\nSimply instantiate and run a ```GCDWebDAVServer``` instance then connect to ```http://{YOUR-IOS-DEVICE-IP-ADDRESS}/``` using a WebDAV client:\n\n```objectivec\n#import \"GCDWebDAVServer.h\"\n\n@interface AppDelegate : NSObject \u003cUIApplicationDelegate\u003e {\n  GCDWebDAVServer* _davServer;\n}\n@end\n\n@implementation AppDelegate\n\n- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {\n  NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];\n  _davServer = [[GCDWebDAVServer alloc] initWithUploadDirectory:documentsPath];\n  [_davServer start];\n  NSLog(@\"Visit %@ in your WebDAV client\", _davServer.serverURL);\n  return YES;\n}\n\n@end\n```\n\nServing a Static Website\n========================\n\nGCDWebServer includes a built-in handler that can recursively serve a directory (it also lets you control how the [\"Cache-Control\"](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9) header should be set):\n\n**macOS version (command line tool):**\n```objectivec\n#import \"GCDWebServer.h\"\n\nint main(int argc, const char* argv[]) {\n  @autoreleasepool {\n    \n    GCDWebServer* webServer = [[GCDWebServer alloc] init];\n    [webServer addGETHandlerForBasePath:@\"/\" directoryPath:NSHomeDirectory() indexFilename:nil cacheAge:3600 allowRangeRequests:YES];\n    [webServer runWithPort:8080];\n    \n  }\n  return 0;\n}\n```\n\nUsing GCDWebServer\n==================\n\nYou start by creating an instance of the ```GCDWebServer``` class. Note that you can have multiple web servers running in the same app as long as they listen on different ports.\n\nThen you add one or more \"handlers\" to the server: each handler gets a chance to handle an incoming web request and provide a response. Handlers are called in a LIFO queue, so the latest added handler overrides any previously added ones.\n\nFinally you start the server on a given port.\n\nUnderstanding GCDWebServer's Architecture\n=========================================\n\nGCDWebServer's architecture consists of only 4 core classes:\n* [GCDWebServer](GCDWebServer/Core/GCDWebServer.h) manages the socket that listens for new HTTP connections and the list of handlers used by the server.\n* [GCDWebServerConnection](GCDWebServer/Core/GCDWebServerConnection.h) is instantiated by ```GCDWebServer``` to handle each new HTTP connection. Each instance stays alive until the connection is closed. You cannot use this class directly, but it is exposed so you can subclass it to override some hooks.\n* [GCDWebServerRequest](GCDWebServer/Core/GCDWebServerRequest.h) is created by the ```GCDWebServerConnection``` instance after HTTP headers have been received. It wraps the request and handles the HTTP body if any. GCDWebServer comes with [several subclasses](GCDWebServer/Requests) of ```GCDWebServerRequest``` to handle common cases like storing the body in memory or stream it to a file on disk.\n* [GCDWebServerResponse](GCDWebServer/Core/GCDWebServerResponse.h) is created by the request handler and wraps the response HTTP headers and optional body. GCDWebServer comes with [several subclasses](GCDWebServer/Responses) of ```GCDWebServerResponse``` to handle common cases like HTML text in memory or streaming a file from disk.\n\nImplementing Handlers\n=====================\n\nGCDWebServer relies on \"handlers\" to process incoming web requests and generating responses. Handlers are implemented with GCD blocks which makes it very easy to provide your own. However, they are executed on arbitrary threads within GCD so __special attention must be paid to thread-safety and re-entrancy__.\n\nHandlers require 2 GCD blocks:\n* The ```GCDWebServerMatchBlock``` is called on every handler added to the ```GCDWebServer``` instance whenever a web request has started (i.e. HTTP headers have been received). It is passed the basic info for the web request (HTTP method, URL, headers...) and must decide if it wants to handle it or not. If yes, it must return a new ```GCDWebServerRequest``` instance (see above) created with this info. Otherwise, it simply returns nil.\n* The ```GCDWebServerProcessBlock``` or ```GCDWebServerAsyncProcessBlock``` is called after the web request has been fully received and is passed the ```GCDWebServerRequest``` instance created at the previous step. It must return synchronously (if using ```GCDWebServerProcessBlock```) or asynchronously (if using ```GCDWebServerAsyncProcessBlock```) a ```GCDWebServerResponse``` instance (see above) or nil on error, which will result in a 500 HTTP status code returned to the client. It's however recommended to return an instance of [GCDWebServerErrorResponse](GCDWebServer/Responses/GCDWebServerErrorResponse.h) on error so more useful information can be returned to the client.\n\nNote that most methods on ```GCDWebServer``` to add handlers only require the ```GCDWebServerProcessBlock``` or ```GCDWebServerAsyncProcessBlock``` as they already provide a built-in ```GCDWebServerMatchBlock``` e.g. to match a URL path with a Regex.\n\nAsynchronous HTTP Responses\n===========================\n\nNew in GCDWebServer 3.0 is the ability to process HTTP requests asynchronously i.e. add handlers to the server which generate their ```GCDWebServerResponse``` asynchronously. This is achieved by adding handlers that use a ```GCDWebServerAsyncProcessBlock``` instead of a ```GCDWebServerProcessBlock```. Here's an example:\n\n**(Synchronous version)** The handler blocks while generating the HTTP response:\n```objectivec\n[webServer addDefaultHandlerForMethod:@\"GET\"\n                         requestClass:[GCDWebServerRequest class]\n                         processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {\n  \n  GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithHTML:@\"\u003chtml\u003e\u003cbody\u003e\u003cp\u003eHello World\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e\"];\n  return response;\n  \n}];\n```\n\n**(Asynchronous version)** The handler returns immediately and calls back GCDWebServer later with the generated HTTP response:\n```objectivec\n[webServer addDefaultHandlerForMethod:@\"GET\"\n                         requestClass:[GCDWebServerRequest class]\n                    asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) {\n  \n  // Do some async operation like network access or file I/O (simulated here using dispatch_after())\n  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\n    GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithHTML:@\"\u003chtml\u003e\u003cbody\u003e\u003cp\u003eHello World\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e\"];\n    completionBlock(response);\n  });\n\n}];\n```\n\n**(Advanced asynchronous version)** The handler returns immediately a streamed HTTP response which itself generates its contents asynchronously:\n```objectivec\n[webServer addDefaultHandlerForMethod:@\"GET\"\n                         requestClass:[GCDWebServerRequest class]\n                         processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {\n  \n  NSMutableArray* contents = [NSMutableArray arrayWithObjects:@\"\u003chtml\u003e\u003cbody\u003e\u003cp\u003e\\n\", @\"Hello World!\\n\", @\"\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e\\n\", nil];  // Fake data source we are reading from\n  GCDWebServerStreamedResponse* response = [GCDWebServerStreamedResponse responseWithContentType:@\"text/html\" asyncStreamBlock:^(GCDWebServerBodyReaderCompletionBlock completionBlock) {\n    \n    // Simulate a delay reading from the fake data source\n    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\n      NSString* string = contents.firstObject;\n      if (string) {\n        [contents removeObjectAtIndex:0];\n        completionBlock([string dataUsingEncoding:NSUTF8StringEncoding], nil);  // Generate the 2nd part of the stream data\n      } else {\n        completionBlock([NSData data], nil);  // Must pass an empty NSData to signal the end of the stream\n      }\n    });\n    \n  }];\n  return response;\n  \n}];\n```\n\n*Note that you can even combine both the asynchronous and advanced asynchronous versions to return asynchronously an asynchronous HTTP response!*\n\nGCDWebServer \u0026 Background Mode for iOS Apps\n===========================================\n\nWhen doing networking operations in iOS apps, you must handle carefully [what happens when iOS puts the app in the background](https://developer.apple.com/library/ios/technotes/tn2277/_index.html). Typically you must stop any network servers while the app is in the background and restart them when the app comes back to the foreground. This can become quite complex considering servers might have ongoing connections when they need to be stopped.\n\nFortunately, GCDWebServer does all of this automatically for you:\n- GCDWebServer begins a [background task](https://developer.apple.com/library/archive/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html) whenever the first HTTP connection is opened and ends it only when the last one is closed. This prevents iOS from suspending the app after it goes in the background, which would immediately kill HTTP connections to the client.\n - While the app is in the background, as long as new HTTP connections keep being initiated, the background task will continue to exist and iOS will not suspend the app **for up to 10 minutes** (unless under sudden and unexpected memory pressure).\n - If the app is still in the background when the last HTTP connection is closed, GCDWebServer will suspend itself and stop accepting new connections as if you had called ```-stop``` (this behavior can be disabled with the ```GCDWebServerOption_AutomaticallySuspendInBackground``` option).\n- If the app goes in the background while no HTTP connections are opened, GCDWebServer will immediately suspend itself and stop accepting new connections as if you had called ```-stop``` (this behavior can be disabled with the ```GCDWebServerOption_AutomaticallySuspendInBackground``` option).\n- If the app comes back to the foreground and GCDWebServer had been suspended, it will automatically resume itself and start accepting again new HTTP connections as if you had called ```-start```.\n\nHTTP connections are often initiated in batches (or bursts), for instance when loading a web page with multiple resources. This makes it difficult to accurately detect when the *very last* HTTP connection has been closed: it's possible 2 consecutive HTTP connections part of the same batch would be separated by a small delay instead of overlapping. It would be bad for the client if GCDWebServer suspended itself right in between. The ```GCDWebServerOption_ConnectedStateCoalescingInterval``` option solves this problem elegantly by forcing GCDWebServer to wait some extra delay before performing any action after the last HTTP connection has been closed, just in case a new HTTP connection is initiated within this delay.\n\nLogging in GCDWebServer\n=======================\n\nBoth for debugging and informational purpose, GCDWebServer logs messages extensively whenever something happens. Furthermore, when building GCDWebServer in \"Debug\" mode versus \"Release\" mode, it logs even more information but also performs a number of internal consistency checks. To enable this behavior, define the preprocessor constant ```DEBUG=1``` when compiling GCDWebServer. In Xcode target settings, this can be done by adding ```DEBUG=1``` to the build setting ```GCC_PREPROCESSOR_DEFINITIONS``` when building in \"Debug\" configuration. Finally, you can also control the logging verbosity at run time by calling ```+[GCDWebServer setLogLevel:]```.\n\nBy default, all messages logged by GCDWebServer are sent to its built-in logging facility, which simply outputs to ```stderr``` (assuming a terminal type device is connected). In order to better integrate with the rest of your app or because of the amount of information logged, you might want to use another logging facility.\n\nGCDWebServer has automatic support for [XLFacility](https://github.com/swisspol/XLFacility) (by the same author as GCDWebServer and also open-source): if it is in the same Xcode project, GCDWebServer should use it automatically instead of the built-in logging facility (see [GCDWebServerPrivate.h](GCDWebServer/Core/GCDWebServerPrivate.h) for the implementation details).\n\nIt's also possible to use a custom logging facility - see [GCDWebServer.h](GCDWebServer/Core/GCDWebServer.h) for more information.\n\nAdvanced Example 1: Implementing HTTP Redirects\n===============================================\n\nHere's an example handler that redirects \"/\" to \"/index.html\" using the convenience method on ```GCDWebServerResponse``` (it sets the HTTP status code and \"Location\" header automatically):\n\n```objectivec\n[self addHandlerForMethod:@\"GET\"\n                     path:@\"/\"\n             requestClass:[GCDWebServerRequest class]\n             processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {\n    \n  return [GCDWebServerResponse responseWithRedirect:[NSURL URLWithString:@\"index.html\" relativeToURL:request.URL]\n                                          permanent:NO];\n    \n}];\n```\n\nAdvanced Example 2: Implementing Forms\n======================================\n\nTo implement an HTTP form, you need a pair of handlers:\n* The GET handler does not expect any body in the HTTP request and therefore uses the ```GCDWebServerRequest``` class. The handler generates a response containing a simple HTML form.\n* The POST handler expects the form values to be in the body of the HTTP request and percent-encoded. Fortunately, GCDWebServer provides the request class ```GCDWebServerURLEncodedFormRequest``` which can automatically parse such bodies. The handler simply echoes back the value from the user submitted form.\n\n```objectivec\n[webServer addHandlerForMethod:@\"GET\"\n                          path:@\"/\"\n                  requestClass:[GCDWebServerRequest class]\n                  processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {\n  \n  NSString* html = @\" \\\n    \u003chtml\u003e\u003cbody\u003e \\\n      \u003cform name=\\\"input\\\" action=\\\"/\\\" method=\\\"post\\\" enctype=\\\"application/x-www-form-urlencoded\\\"\u003e \\\n      Value: \u003cinput type=\\\"text\\\" name=\\\"value\\\"\u003e \\\n      \u003cinput type=\\\"submit\\\" value=\\\"Submit\\\"\u003e \\\n      \u003c/form\u003e \\\n    \u003c/body\u003e\u003c/html\u003e \\\n  \";\n  return [GCDWebServerDataResponse responseWithHTML:html];\n  \n}];\n\n[webServer addHandlerForMethod:@\"POST\"\n                          path:@\"/\"\n                  requestClass:[GCDWebServerURLEncodedFormRequest class]\n                  processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {\n  \n  NSString* value = [[(GCDWebServerURLEncodedFormRequest*)request arguments] objectForKey:@\"value\"];\n  NSString* html = [NSString stringWithFormat:@\"\u003chtml\u003e\u003cbody\u003e\u003cp\u003e%@\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e\", value];\n  return [GCDWebServerDataResponse responseWithHTML:html];\n  \n}];\n```\n\nAdvanced Example 3: Serving a Dynamic Website\n=============================================\n\nGCDWebServer provides an extension to the ```GCDWebServerDataResponse``` class that can return HTML content generated from a template and a set of variables (using the format ```%variable%```). It is a very basic template system and is really intended as a starting point to building more advanced template systems by subclassing ```GCDWebServerResponse```.\n\nAssuming you have a website directory in your app containing HTML template files along with the corresponding CSS, scripts and images, it's pretty easy to turn it into a dynamic website:\n\n```objectivec\n// Get the path to the website directory\nNSString* websitePath = [[NSBundle mainBundle] pathForResource:@\"Website\" ofType:nil];\n\n// Add a default handler to serve static files (i.e. anything other than HTML files)\n[self addGETHandlerForBasePath:@\"/\" directoryPath:websitePath indexFilename:nil cacheAge:3600 allowRangeRequests:YES];\n\n// Add an override handler for all requests to \"*.html\" URLs to do the special HTML templatization\n[self addHandlerForMethod:@\"GET\"\n                pathRegex:@\"/.*\\.html\"\n             requestClass:[GCDWebServerRequest class]\n             processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {\n    \n    NSDictionary* variables = [NSDictionary dictionaryWithObjectsAndKeys:@\"value\", @\"variable\", nil];\n    return [GCDWebServerDataResponse responseWithHTMLTemplate:[websitePath stringByAppendingPathComponent:request.path]\n                                                    variables:variables];\n    \n}];\n\n// Add an override handler to redirect \"/\" URL to \"/index.html\"\n[self addHandlerForMethod:@\"GET\"\n                     path:@\"/\"\n             requestClass:[GCDWebServerRequest class]\n             processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {\n    \n    return [GCDWebServerResponse responseWithRedirect:[NSURL URLWithString:@\"index.html\" relativeToURL:request.URL]\n                                            permanent:NO];\n    \n];\n\n```\n\nFinal Example: File Downloads and Uploads From iOS App\n======================================================\n\nGCDWebServer was originally written for the [ComicFlow](http://itunes.apple.com/us/app/comicflow/id409290355?mt=8) comic reader app for iPad. It allow users to connect to their iPad with their web browser over WiFi and then upload, download and organize comic files inside the app.\n\nComicFlow is [entirely open-source](https://github.com/swisspol/ComicFlow) and you can see how it uses GCDWebServer in the [WebServer.h](https://github.com/swisspol/ComicFlow/blob/master/Classes/WebServer.h) and [WebServer.m](https://github.com/swisspol/ComicFlow/blob/master/Classes/WebServer.m) files.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftimoliver%2Fwebserverkit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftimoliver%2Fwebserverkit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftimoliver%2Fwebserverkit/lists"}