2
头图

Preface

Recently, my team and I have developed two APP .

On the client side, Flutter is used to facilitate cross-platform.

Server-side aspects sword easy road, did not use php , pythod , java and the like, instead of using the Flutter same Dart language.

Looking back on the whole process, I felt that I was not lightly burned (sao), and I wrote this article as a record of my illness. If there are other young talents, there are also Dart develop the server, you can have a reference.

Why I thought of using Dart to develop the server

Many developers have heard of the Dart language, which started Flutter the client development framework 060e15570a6445.

Using the Flutter framework to develop cross-platform applications can ensure the consistency of each platform and the use experience consistent with the native language, while improving work efficiency and reducing repetitive work costs. Based on the Dart language and using the Flutter framework, many satisfactory client applications have been developed, and major companies are also actively promoting work in this area.

In fact, the Dart language is not only suitable for client-side development. Similarly, Dart can also be used for server-side development.

The important features of Dart

Dart supports static compilation. Compared with PHP , Pythod and other languages, it can have higher execution performance.
Dart supports asynchronous tasks. Compared with Java , it naturally supports high concurrency.
Dart supports object-oriented, which is easier to model and understand Go

There is another point that needs special reminder:

Dart has achieved obvious success in the field of client-side development. If Dart is also used in the field of server-side, it can reuse code more, reduce communication costs, and improve development efficiency.

Therefore, using the Dart language for server-side development is a thing worth trying.

Write the first line of server code

In Dart , everything is so primitive and barren at present, even the WEB server needs to be written by itself.

Create a new file main.dart

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 , opened the HTTP service, and received the HTTP request,

Open the browser and visit localhost:4040 to see the browser output Hello, world!

The code still looks very simple and not complicated.

Simple routing is used first

From the above code, it can also be seen that HttpRequest is generated when we visit the web page address in the browser, and we guess that it should contain the request information.

Sure enough, open HttpRequest , you can see a lot of information, such as:

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

As you can see, they are all very common concepts WEB

Among uri , there is path , which is the request path, that is:

When you request the \ path in the browser, the value of request.uri.path is \
When you request the \abc path in the browser, the value of request.uri.path is \abc
When you request the \admin path in the browser, the value of request.uri.path is \admin

Then it’s easy to handle things, if , else get 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();
  }
}

Hmm, there is still need for optimization, let's take a look at the effect first.

Simple controller to use

The controller is generally used to receive the request information, then call the internal code of the system to process the information, and finally return the response information.

Stop talking nonsense and get the code.

Create a new file HomeController.dart , enter the following code

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';
  }
}

Import the controller in main.dart 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();
}

Hmm, I still need to optimize here, I'll talk about it later.

Simple database operation

In the project dependent files pubspec.yaml add a new dependency mysql1: ^0.19.2

Use mysql1 for 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]}');
});

Write SQL directly, you can't lose a lot of hair, just encapsulate it again

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

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

print(list);

Hmm, chain operation is much easier to use.

to sum up

So far, we have used the Dart language to realize the request from the browser, to the routing, to the controller, and to operate the database.

Of course, it is very simple, and it needs other work to actually use it.

But (must add but), at least we have verified the Dart develop the server, and there is another choice in the technical selection of back-end development.

What do you guys say?


汤哥搞开发
34 声望4 粉丝