当前位置:网站首页>Dart development server, do I have a fever?

Dart development server, do I have a fever?

2022-06-24 08:09:00 Tangge engages in development

Preface

recently , My team and I have developed two APP.

The client side uses Flutter, Convenient cross platform .

On the service side, the sword is on the wrong side , There is no php, pythod, java And so on. , But with Flutter Same Dart Language .

Review the whole process , Feel burned ( SAO ) It's not light , Write down this article , It's all about recording the illness . If there are other young talents , Also have Dart The idea of developing a server , There can be a reference .

Why did I think of using Dart Development server

Many developers have heard that Dart Language , It's from Flutter This client-side development framework starts with .

Use Flutter Framework to develop cross platform applications , It can ensure the consistency of all platforms to the greatest extent , And the use experience consistent with the native language , At the same time, improve work efficiency , Reduce the cost of repetitive work . be based on Dart Language , Use Flutter frame , At present, many satisfactory client applications have been developed , Major companies are also actively promoting this work .

actually ,Dart Language is not only suitable for client-side development , alike ,Dart It can also be developed as a server .

Dart The important features are as follows :

Dart Support static compilation , Comparison PHP , Pythod Other languages , Can have higher execution performance .

Dart Support asynchronous tasks , Comparison Java etc. , Born to support high concurrency .

Dart Support for object-oriented , Comparison Go etc. , Easier to model and understand .

One other thing , Need special reminders :

Dart In the field of client development , It has achieved obvious success , If it is also used in the server field Dart, You can reuse code at a higher level , Reduce communication costs , Improve development efficiency .

therefore , Use Dart Language for server-side development , It is a thing worth trying .

Write the first line of the server code

stay Dart In the server world of , At present, everything is so primitive and desolate , Even WEB Servers need to be written by themselves .

newly build main.dart file

import 'dart:io';

main() async {
  var server = await HttpServer.bind(
    InternetAddress.loopbackIPv4,
    4040,
  );
  print('Listening on localhost:${server.port}');

  await for (HttpRequest request in server) {
    request.response
      ..write('Hello, world!')
      ..close();
  }
}

The above code , On the local computer 4040 port , Open the HTTP service , And receive HTTP request ,

Open the browser , visit localhost:4040 You can see the browser output Hello, world!

The code still looks simple , Not complicated .

Simple routes are used first

From the code above , You can see , HttpRequest It is generated when the browser accesses the web address , We guess he should have included the requested information .

Sure enough , open HttpRequest Source code , You can see a lot of information , such as :

  1. method
  2. uri
  3. headers
  4. cookies
  5. session
  6. connectionInfo

You can see , Are some very common WEB Concept .

among uri Next there is path , That is, the request path , in other words :

When you request in the browser \ Path time , request.uri.path The value is \

When you request in the browser \abc Path time , request.uri.path The value is \abc

When you request in the browser \admin Path time , request.uri.path The value is \admin

Then it's easy to do , if, else Walk up

import 'dart:io';

main() async {
  var server = await HttpServer.bind(
    InternetAddress.loopbackIPv4,
    4040,
  );
  print('Listening on localhost:${server.port}');

  await for (HttpRequest request in server) {
    routeHandle(request);
  }
}

void routeHandle(HttpRequest request) {
  if (request.uri.path == '/abc') {
    request.response
      ..write('Hello, abc!')
      ..close();
  } else if (request.uri.path == '/admin') {
    request.response
      ..write('Hello, admin!')
      ..close();
  } else {
    request.response
      ..write('Hello, world!')
      ..close();
  }
}

Mm-hmm , There is also a need to optimize , First look at the effect .

Simple controller to use

The controller is generally used to receive request information , Then call the system internal code to process the information , Finally, the response information is returned .

Don't talk nonsense , Get the code .

New file HomeController.dart, Type the following

import 'dart:io';

class HomeController {
  static String index(HttpRequest request) {
    // some other code
    return 'hello world';
  }

  static String abc(HttpRequest request) {
    // some other code
    return 'hello abc';
  }

  static String admin(HttpRequest request) {
    // some other code
    return 'hello admin';
  }
}

stay main.dart Import the controller , And modify the content

import 'dart:io';
import 'HomeController.dart';

main() async {
  var server = await HttpServer.bind(
    InternetAddress.loopbackIPv4,
    4040,
  );
  print('Listening on localhost:${server.port}');

  await for (HttpRequest request in server) {
    routeHandle(request);
  }
}

void routeHandle(HttpRequest request) {
  String content = '';

  if (request.uri.path == '/abc') {
    content = HomeController.abc(request);
  } else if (request.uri.path == '/admin') {
    content = HomeController.admin(request);
  } else {
    content = HomeController.index(request);
  }

  request.response
    ..write(content)
    ..close();
}

Mm-hmm , There is also a need to optimize , later .

Simple database operations work

In the project dependency file pubspec.yaml Add new dependency mysql1: ^0.19.2

Use mysql1 A simple query

ConnectionSettings settings = new ConnectionSettings(
  host: 'localhost', 
  port: 3306,
  user: 'bob',
  password: 'wibble',
  db: 'mydb'
);
MySqlConnection conn = await MySqlConnection.connect(settings);

var results = await conn.query('select name, email from users where id = ?', [1]);

for (var row in results) {
  print('Name: ${row[0]}, email: ${row[1]}');
});

direct writing SQL, That won't lose a lot of hair , Simply package it and come back

List<Column> condition = [Column('id', '=', 1)];

List<Map<String,dynamic>> list = await Db('users').where(condition).select();

print(list);

Mm-hmm , Chain operation , It's much more convenient to use .

summary

thus , We use Dart Language , Realize the request from the browser , To route , To the controller , And can operate the database .

Of course it's very simple , It needs other work to really use it .

however ( Be sure to add buts ), At least we verified Dart The feasibility of developing the server , There is another choice in the technology selection of back-end development .

What do you say ?

原网站

版权声明
本文为[Tangge engages in development]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/06/20210628163530017c.html