Go
This commit is contained in:
parent
1d42e8b0eb
commit
81a4081441
4 changed files with 36 additions and 16 deletions
|
@ -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
16
example/basic.dart
Normal 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}');
|
||||
}
|
|
@ -1,20 +1,22 @@
|
|||
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
|
||||
/// `User-Agent` header will throw a `400 Bad Request`.
|
||||
/// 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;
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue