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 # user_agent
Middleware to inject a User Agent object into requests. 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: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. /// Injects a [UserAgent] into requests.
/// ///
/// If [strict] is `true`, then an invalid /// If [strict] is `true`, then requests without a user agent will be rejected.
/// `User-Agent` header will throw a `400 Bad Request`.
RequestMiddleware parseUserAgent({bool strict: true}) { RequestMiddleware parseUserAgent({bool strict: true}) {
return (req, res) async { return (RequestContext req, res) async {
try { var agentString = req.headers.value('user-agent');
final client = ua.parse(req.headers.value('User-Agent'));
req if (agentString == null) {
..inject(ua.Client, client) throw new AngelHttpException.badRequest(
..inject(ua.UserAgent, client.userAgent); message: 'User-Agent header is required.');
} catch (e) { } else if (agentString != null) {
throw strict ? Map<String, List<String>> map = {};
new AngelHttpException.BadRequest(message: 'Invalid user agent.') : e; req.headers.forEach((k, v) => map[k] = v);
req.inject(UserAgent, new UserAgent(agentString, headers: map));
} }
return true; return true;
}; };
} }

View file

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