Http Client in Dart

Here’s the translation of the HTTP Client example from Go to Dart, formatted in Markdown suitable for Hugo:

Our example demonstrates how to make HTTP requests in Dart using the http package. We’ll use it to issue simple HTTP requests.

import 'dart:io';
import 'package:http/http.dart' as http;

void main() async {
  // Issue an HTTP GET request to a server. The http.get function
  // is a convenient way to send a GET request.
  try {
    final response = await http.get(Uri.parse('https://gobyexample.com'));

    // Print the HTTP response status.
    print('Response status: ${response.statusCode}');

    // Print the first 5 lines of the response body.
    final lines = response.body.split('\n');
    for (var i = 0; i < 5 && i < lines.length; i++) {
      print(lines[i]);
    }
  } catch (e) {
    print('An error occurred: $e');
  }
}

To run this program, you need to have the http package in your pubspec.yaml file:

dependencies:
  http: ^0.13.3

Then, you can run the program:

$ dart run http_client.dart
Response status: 200
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Go by Example</title>

In this Dart version:

  1. We import the http package, which provides a simple way to make HTTP requests.

  2. The main function is marked as async because we’re using await for the HTTP request.

  3. We use http.get to send a GET request to the specified URL. This returns a Future<Response>, which we await.

  4. We print the response status code using response.statusCode.

  5. To print the first 5 lines of the response body, we split the body into lines and use a for loop to print the first 5.

  6. We wrap our code in a try-catch block to handle any potential errors.

Note that Dart’s approach to HTTP requests is somewhat simpler than Go’s, as it doesn’t require explicit closing of the response body or use of a scanner. The http package handles these details for us.

Dart’s async-await syntax provides a clean way to work with Futures, which are similar to Go’s goroutines and channels for handling asynchronous operations.