platform/lib/angel.dart

23 lines
648 B
Dart
Raw Normal View History

2016-12-12 04:32:26 +00:00
import 'package:angel_framework/angel_framework.dart';
2016-12-12 04:35:12 +00:00
import 'package:user_agent/user_agent.dart' as ua;
2016-12-12 04:32:26 +00:00
2016-12-12 04:35:12 +00:00
/// Injects a [ua.UserAgent] into requests.
2016-12-12 04:32:26 +00:00
///
/// If [strict] is `true`, then an invalid
/// `User-Agent` header will throw a `400 Bad Request`.
RequestMiddleware parseUserAgent({bool strict: true}) {
return (req, res) async {
try {
2016-12-12 04:35:12 +00:00
req.inject(ua.UserAgent, ua.parse(req.headers.value('User-Agent')));
2016-12-12 04:32:26 +00:00
} catch (e) {
2016-12-12 04:35:12 +00:00
if (e is ua.UserAgentException && strict) {
2016-12-12 04:32:26 +00:00
throw new AngelHttpException.BadRequest(message: 'Invalid user agent.');
} else {
rethrow;
}
}
return true;
};
}