Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 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 All @@ -11,7 +12,7 @@ Future<Null> main(final List<String> args) async {
"h": "help"
};
final Map<String, dynamic> cmdLineArgsMap = _parseCmdLineArgs(args, SHORTHAND_TO_FULL_CMD_LINE_ARG_KEYS);
InternetAddress hostAddr = InternetAddress.ANY_IP_V4;
InternetAddress hostAddr = io.InternetAddress.anyIPv4;
int portNumber = 8080; // Default value.

if (cmdLineArgsMap.containsKey('help')) {
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
3 changes: 2 additions & 1 deletion example/virtual_directory.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import "dart:io";
import "dart:async";
import "package:dart2_constant/io.dart" as io;
import "package:web_server/web_server.dart" as webServer;

Future<Null> main() async {
// Initialize the WebServer
final webServer.WebServer localWebServer = new webServer.WebServer(InternetAddress.ANY_IP_V4, 8080,
final webServer.WebServer localWebServer = new webServer.WebServer(io.InternetAddress.anyIPv4, 8080,
hasHttpServer: true);

// Log out some of the connection information.
Expand Down
11 changes: 6 additions & 5 deletions example/web_server_misc.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import "dart:io";
import "package:dart2_constant/io.dart" as io;
import "package:web_server/web_server.dart";

void main() {
// Initialize and bind the HTTP and WebSocket WebServer
final WebServer localWebServer = new WebServer(InternetAddress.ANY_IP_V4, 8080,
final WebServer localWebServer = new WebServer(io.InternetAddress.anyIPv4, 8080,
hasHttpServer: true, hasWebSocketServer: true);

// Log out some of the connection information
Expand Down Expand Up @@ -41,23 +42,23 @@ void main() {

// Respond to the Url request
httpRequest.response
..headers.contentType = ContentType.JSON // Set the 'content-type' header as JSON
..headers.contentType = io.ContentType.json // Set the 'content-type' header as JSON
..write(apiResponse.toJsonEncoded()) // Export as a JSON encoded string
..close();
})

// 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());
}
}
48 changes: 25 additions & 23 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 @@ -242,12 +242,12 @@ class HttpServerRequestHandler {

_AuthCheckResults _checkAuthFromRequest(final HttpRequest httpRequest, final _PathDataWithAuth acceptedCredentialsPathData) {
// If no auth header supplied
if (httpRequest.headers.value(HttpHeaders.AUTHORIZATION) == null) {
if (httpRequest.headers.value(io.HttpHeaders.authorizationHeader) == null) {
return const _AuthCheckResults(false);
}

const int MAX_ALLOWED_CHARACTER_RANGE = 256;
final String authHeaderStr = httpRequest.headers.value(HttpHeaders.AUTHORIZATION); // Get the provided auth info
final String authHeaderStr = httpRequest.headers.value(io.HttpHeaders.authorizationHeader); // Get the provided auth info
final int trimRange = (authHeaderStr.length <= MAX_ALLOWED_CHARACTER_RANGE) ? authHeaderStr.length : MAX_ALLOWED_CHARACTER_RANGE; // Determine subStr amt
final String clientProvidedAuthInfo = authHeaderStr.substring(0, trimRange).replaceFirst(new RegExp('^Basic '), ''); // Remove the prefixed "Basic " from auth header

Expand All @@ -261,16 +261,16 @@ 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
..headers.add(HttpHeaders.WWW_AUTHENTICATE, 'Basic realm="Enter credentials"')
..statusCode = io.HttpStatus.unauthorized
..headers.add(io.HttpHeaders.wwwAuthenticateHeader, 'Basic realm="Enter credentials"')
..write(errMessage)
..close();
}

/// 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));
});
}
}
8 changes: 6 additions & 2 deletions pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
name: web_server
version: 2.0.0+3
version: 2.0.1
author: Brandon White <jennexproject+webserver@gmail.com>
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 @@ -16,5 +16,9 @@ dependencies:
server_logger:
git: https://github.com/bwhite000/server-logger.git
version: '>=0.1.0 <2.0.0'
dart2_constant:
git:
url: https://github.com/Stargator/dart2_constant.git
ref: 1.0.3+dart2
executables:
web_server: