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:
We import the
http
package, which provides a simple way to make HTTP requests.The
main
function is marked asasync
because we’re usingawait
for the HTTP request.We use
http.get
to send a GET request to the specified URL. This returns aFuture<Response>
, which we await.We print the response status code using
response.statusCode
.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.
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.