Skip to content

Commit

Permalink
Enable Dart 2.0 support
Browse files Browse the repository at this point in the history
  • Loading branch information
Stargator committed Aug 9, 2018
1 parent 3931190 commit 9e97979
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 40 deletions.
9 changes: 5 additions & 4 deletions bin/web_server.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import "dart:io";
import "dart:async";
import "package:dart2_constant/io.dart" as io;
import "package:web_server/web_server.dart" as webServer;

/**
Expand Down Expand Up @@ -48,15 +49,15 @@ Future<Null> main(final List<String> args) async {

// Handle errors
localWebServer.httpServerHandler
..onErrorDocument(HttpStatus.NOT_FOUND, (final HttpRequest httpRequest) {
..onErrorDocument(io.HttpStatus.notFound, (final HttpRequest httpRequest) {
// Use the helper method from this WebServer package
webServer.HttpServerRequestHandler.sendPageNotFoundResponse(httpRequest,
'<h1>${HttpStatus.NOT_FOUND} - Page not found</h1>');
'<h1>${io.HttpStatus.notFound} - Page not found</h1>');
})
..onErrorDocument(HttpStatus.INTERNAL_SERVER_ERROR, (final HttpRequest httpRequest) {
..onErrorDocument(io.HttpStatus.internalServerError, (final HttpRequest httpRequest) {
// Use the helper method from this WebServer package
webServer.HttpServerRequestHandler.sendInternalServerErrorResponse(httpRequest,
'<h1>${HttpStatus.INTERNAL_SERVER_ERROR} - Internal Server Error</h1>');
'<h1>${io.HttpStatus.internalServerError} - Internal Server Error</h1>');
});
}

Expand Down
7 changes: 4 additions & 3 deletions example/web_server_misc.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import "dart:io";
import "package:dart2_constant/io.dart" as io;
import "package:web_server/web_server.dart";

void main() {
Expand Down Expand Up @@ -47,17 +48,17 @@ void main() {
})

// Add a custom function for handling the request in case of the error code supplied as the parameter.
..onErrorDocument(HttpStatus.NOT_FOUND, (final HttpRequest httpRequest) {
..onErrorDocument(io.HttpStatus.notFound, (final HttpRequest httpRequest) {
httpRequest.response
..statusCode = HttpStatus.NOT_FOUND
..statusCode = io.HttpStatus.notFound
..headers.contentType = new ContentType('text', 'html', charset: 'utf-8')
..write('<h1>404 Error accessing: ${httpRequest.requestedUri.path}</h1>')
..close();
});

// Attach WebSocket command listeners and base events
localWebServer.webSocketServerHandler
..on[0].listen((final WebSocketRequestPayload requestPayload) { /*...*/ })
..on[0].listen((final dynamic requestPayload) { /*...*/ })
..onConnectionOpen.listen((final WebSocketConnectionData connectionData) { /*...*/ })
..onConnectionError.listen((final WebSocket webSocket) { /*...*/ })
..onConnectionClose.listen((final WebSocket webSocket) { /*...*/ });
Expand Down
4 changes: 2 additions & 2 deletions lib/src/web_server/api_response.dart
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class ApiResponse {
* Calls [toJson], then processes it through [JSON.encode()] before returning.
*/
String toJsonEncoded() {
return JSON.encode(this.toJson());
return convert.json.encode(this.toJson());
}
}

Expand Down Expand Up @@ -112,6 +112,6 @@ class ApiErrorResponse {
}

String toJsonEncoded() {
return JSON.encode(this.toJson());
return convert.json.encode(this.toJson());
}
}
42 changes: 22 additions & 20 deletions lib/src/web_server/http_server_request_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ class HttpServerRequestHandler {
} else { // Respond with 404 error because nothing was matched.
if (HttpServerRequestHandler.shouldBeVerbose) ServerLogger.log('No registered url match found.');

this._callListenerForErrorDocument(HttpStatus.NOT_FOUND, httpRequest);
this._callListenerForErrorDocument(io.HttpStatus.notFound, httpRequest);
}
}
}
Expand Down Expand Up @@ -261,7 +261,7 @@ class HttpServerRequestHandler {
/// Helper for sending an HTTP 401 Auth required response
static void sendRequiredBasicAuthResponse(final HttpRequest httpRequest, final String errMessage) {
httpRequest.response
..statusCode = HttpStatus.UNAUTHORIZED
..statusCode = io.HttpStatus.unauthorized
..headers.add(HttpHeaders.WWW_AUTHENTICATE, 'Basic realm="Enter credentials"')
..write(errMessage)
..close();
Expand All @@ -270,7 +270,7 @@ class HttpServerRequestHandler {
/// Helper for sending a HTTP 404 response with an optional custom HTML error message.
static void sendPageNotFoundResponse(final HttpRequest httpRequest, [final String responseVal = '404 - Page not found']) {
httpRequest.response
..statusCode = HttpStatus.NOT_FOUND
..statusCode = io.HttpStatus.notFound
..headers.contentType = new ContentType('text', 'html', charset: 'utf-8')
..write(responseVal)
..close();
Expand All @@ -279,7 +279,7 @@ class HttpServerRequestHandler {
/// Helper for sending an HTTP 500 response with an optional custom HTML error message.
static void sendInternalServerErrorResponse(final HttpRequest httpRequest, [final String responseVal = '500 - Internal Server Error']) {
httpRequest.response
..statusCode = HttpStatus.INTERNAL_SERVER_ERROR
..statusCode = io.HttpStatus.internalServerError
..headers.contentType = new ContentType('text', 'html', charset: 'utf-8')
..write(responseVal)
..close();
Expand Down Expand Up @@ -320,26 +320,28 @@ class HttpServerRequestHandler {

this._possibleFiles[urlData.path] = urlData.id;

this._functionStore[urlData.id].listen((final HttpRequest httpRequest) async {
String _localFileContents;
this._functionStore[urlData.id].listen((final dynamic httpRequest) async {
if (httpRequest is HttpRequest) {
String _localFileContents;

if (enableCaching == true) { // Use a cached file, or initialize the cached file, if enabled
if (_fileContents == null) { // If a version has not been cached before
_fileContents = await file.readAsString();
}
if (enableCaching == true) { // Use a cached file, or initialize the cached file, if enabled
if (_fileContents == null) { // If a version has not been cached before
_fileContents = await file.readAsString();
}

_localFileContents = _fileContents;
} else if (enableCaching == false) { // Read freshly, if caching is not enabled
_localFileContents = await file.readAsString();
}
_localFileContents = _fileContents;
} else if (enableCaching == false) { // Read freshly, if caching is not enabled
_localFileContents = await file.readAsString();
}

if (_contentType != null) {
httpRequest.response.headers.contentType = _contentType;
}
if (_contentType != null) {
httpRequest.response.headers.contentType = _contentType;
}

httpRequest.response
httpRequest.response
..write(_localFileContents)
..close();
}
});
} else {
if (HttpServerRequestHandler.shouldBeVerbose) ServerLogger.error('The file at path ($pathToFile) was not found in the filesystem; unable to serve it.');
Expand Down Expand Up @@ -440,7 +442,7 @@ class HttpServerRequestHandler {
final FileStat fileStat = await entity.stat();

// Don't process if this is not a file.
if (fileStat.type != FileSystemEntityType.FILE) {
if (fileStat.type != io.FileSystemEntityType.file) {
return;
}

Expand Down Expand Up @@ -558,7 +560,7 @@ class HttpServerRequestHandler {
} else { // File not found
if (HttpServerRequestHandler.shouldBeVerbose) ServerLogger.error('_HttpServerRequestHandler::_serveStandardFile(String, HttpRequest) - File not found at path: ($pathToFile)');

this._callListenerForErrorDocument(HttpStatus.NOT_FOUND, httpRequest);
this._callListenerForErrorDocument(io.HttpStatus.notFound, httpRequest);
}
} catch(err, stackTrace) {
ServerLogger.error(err);
Expand Down
10 changes: 6 additions & 4 deletions lib/src/web_server/web_socket_server_request_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,14 @@ class _WebSocketServerRequestHandler {

webSocket.map((final dynamic message) {
if ((message is String) == false) {
return JSON.decode(this.customDecodeMessage(message, httpRequest, webSocket));
return convert.json.decode(this.customDecodeMessage(message, httpRequest, webSocket));
}

return JSON.decode(message);
}).listen((final Map<String, dynamic> json) {
this.onMessage(json, httpRequest, webSocket);
return convert.json.decode(message);
}).listen((final dynamic json) {
if (json is Map<String, dynamic>) {
this.onMessage(json, httpRequest, webSocket);
}
}, onError: (final dynamic err) {
ServerLogger.error(err);

Expand Down
7 changes: 4 additions & 3 deletions lib/web_server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ library WebServer;

import "dart:io";
import "dart:async";
import "dart:convert" show JSON, UTF8, LineSplitter;
import "dart:typed_data";
import "package:cache/cache.dart";
import 'package:dart2_constant/convert.dart' as convert;
import 'package:dart2_constant/io.dart' as io;
import "package:event_listener/event_listener.dart";
import "package:path/path.dart" as path;
import "package:server_logger/server_logger.dart" as ServerLogger;
Expand Down Expand Up @@ -91,7 +92,7 @@ class WebServer {
(this.allowedMethods != null && this.allowedMethods.contains(httpRequest.method) == false))
{
httpRequest.response
..statusCode = HttpStatus.FORBIDDEN
..statusCode = io.HttpStatus.forbidden
..close();
return;
}
Expand All @@ -107,7 +108,7 @@ class WebServer {
this.httpServerHandler._onHttpRequest(httpRequest);
} else {
httpRequest.response
..statusCode = HttpStatus.FORBIDDEN
..statusCode = io.HttpStatus.forbidden
..close();
}
}
Expand Down
4 changes: 2 additions & 2 deletions lib/web_socket_connection_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
library WebSocketConnectionManager;

import "dart:io";
import "dart:convert" show JSON;
import "package:dart2_constant/convert.dart" as convert;
import "package:server_logger/server_logger.dart" as ServerLogger;

part 'src/web_socket_connection_manager/web_socket_object_store.dart';
Expand All @@ -19,7 +19,7 @@ abstract class WebSocketConnectionManager {
ServerLogger.log('Broadcasting message to (${WebSocketConnectionManager.objectStore.length}) clients: \n$message');

WebSocketConnectionManager.objectStore.values.forEach((final WebSocketConnection webSocketConnection) {
webSocketConnection.webSocket.add(JSON.encode(message));
webSocketConnection.webSocket.add(convert.json.encode(message));
});
}
}
12 changes: 10 additions & 2 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ author: Brandon White <[email protected]>
description: An efficient server library for quickly creating a WebServer and handling HTTP requests, WebSocket connections, and API requests.
homepage: https://github.com/bwhite000/web-server
environment:
sdk: '>=1.9.0 <2.0.0'
sdk: '>=1.9.0 <3.0.0'
documentation: http://jennex.it/github/bwhite000/web-server/docs/
dependencies:
cache:
Expand All @@ -17,4 +17,12 @@ dependencies:
git: https://github.com/bwhite000/server-logger.git
version: '>=0.1.0 <2.0.0'
executables:
web_server:
web_server:

dependency_overrides:
cache:
path: "/Users/johnmcmahon/Workspace/GitHub/Stargator/cache"
server_logger:
path: "/Users/johnmcmahon/Workspace/GitHub/Stargator/server-logger"
event_listener:
path: "/Users/johnmcmahon/Workspace/GitHub/Stargator/event-listener"

0 comments on commit 9e97979

Please sign in to comment.