代码示例
import 'aqueduct/aqueduct.dart'; class MyAppChannel extends ApplicationChannel { @override Future prepare() async { // 初始化数据库连接等操作 } @override Controller get entryPoint { final router = Router(); // 1. 网站端口为6081 router.route('/').linkFunction((request) async { return Response.ok('Hello, world!') ..contentType = ContentType.html; }); // 2. 使用orm接口进行数据增删查改访问,过程要求通过非ID字段进行查找数据 router.route('/items').link(() => ItemsController(context)); // 3. 使用token进行权限验证 router.route('/secure').link(() => SecureController()); // 4. 接收前端上传的图片文件并保存 router.route('/upload').link(() => UploadController()); return router; } } class ItemsController extends ResourceController { final ManagedContext context; ItemsController(this.context); @Operation.get() Future<Response> getItems(@Bind.query('name') String name) async { final query = Query<Item>(context) ..where((item) => item.name).equalTo(name); final items = await query.fetch(); // 5. 将数据库返回的false和true转化为可授权和不可授权后返回前端 final transformedItems = items.map((item) { return { 'name': item.name, 'authorized': item.authorized ? '可授权' : '不可授权' }; }).toList(); // 6. 返回前端的数据中带有前端自己的访问ip final clientIP = request.connectionInfo.remoteAddress.address; return Response.ok(transformedItems) ..contentType = ContentType.json ..write(clientIP); } } class SecureController extends ResourceController { @Operation.get() Future<Response> getSecureData() async { // 验证token逻辑 if (/* token验证通过 */) { return Response.ok('Secure Data'); } else { return Response.forbidden(); } } } class UploadController extends ResourceController { @Operation.post() Future<Response> uploadFile(@Bind.multipart('file') FileUpload file) async { // 保存上传的文件逻辑 final savedFilePath = /* 保存文件的路径 */; return Response.ok('File uploaded: $savedFilePath'); } } class Item extends ManagedObject<_Item> implements _Item {} class _Item { @primaryKey int id; @Column(unique: true) String name; @Column(defaultValue: 'false') bool authorized; } Future main() async { final app = Application<MyAppChannel>() ..options.configurationFilePath = 'config.yaml'; await app.start(numberOfInstances: 3); }
标签:经验,return,name,aqueduct,class,router,async,final From: https://www.cnblogs.com/pearlcity/p/17925696.html