This commit is contained in:
thosakwe 2017-01-14 14:14:20 -05:00
parent 1d42e8b0eb
commit 81a4081441
4 changed files with 36 additions and 16 deletions

View file

@ -1,2 +1,3 @@
# user_agent
Middleware to inject a User Agent object into requests.
For convenience's sake, it also exports the `user_agent` library.

16
example/basic.dart Normal file
View file

@ -0,0 +1,16 @@
import 'dart:io';
import 'package:angel_framework/angel_framework.dart';
import 'package:angel_user_agent/angel_user_agent.dart';
main() async {
var app = new Angel()..before.add(parseUserAgent(strict: true));
app.get(
'/',
(UserAgent ua) => ua.isChrome
? 'Woohoo! You are running Chrome.'
: 'Sorry, we only support Google Chrome.');
var server = await app.startServer(InternetAddress.ANY_IP_V4, 3000);
print('Listening at http://${server.address.address}:${server.port}');
}

View file

@ -1,22 +1,24 @@
import 'package:angel_framework/angel_framework.dart';
import 'package:ua_parser/ua_parser.dart' as ua;
import 'package:user_agent/user_agent.dart';
export 'package:user_agent/user_agent.dart';
/// Injects a [ua.Client] and [ua.UserAgent] into requests.
///
/// If [strict] is `true`, then an invalid
/// `User-Agent` header will throw a `400 Bad Request`.
/// Injects a [UserAgent] into requests.
///
/// If [strict] is `true`, then requests without a user agent will be rejected.
RequestMiddleware parseUserAgent({bool strict: true}) {
return (req, res) async {
try {
final client = ua.parse(req.headers.value('User-Agent'));
req
..inject(ua.Client, client)
..inject(ua.UserAgent, client.userAgent);
} catch (e) {
throw strict ?
new AngelHttpException.BadRequest(message: 'Invalid user agent.') : e;
return (RequestContext req, res) async {
var agentString = req.headers.value('user-agent');
if (agentString == null) {
throw new AngelHttpException.badRequest(
message: 'User-Agent header is required.');
} else if (agentString != null) {
Map<String, List<String>> map = {};
req.headers.forEach((k, v) => map[k] = v);
req.inject(UserAgent, new UserAgent(agentString, headers: map));
}
return true;
};
}

View file

@ -6,4 +6,5 @@ homepage: https://github.com/angel-dart/user_agent
environment:
sdk: ">=1.19.0"
dependencies:
ua_parser: ^1.0.0
angel_framework: ^1.0.0-dev
user_agent: ^1.0.0-beta