http_serving library

Features for serving HTTP requests on Google Cloud Platform.

This library provides functions to run a shelf server that handles requests in a way that is compatible with Google Cloud environments like Cloud Run and Cloud Functions. It includes middleware for logging requests in the format expected by Google Cloud Logging.

Example

import 'package:google_cloud/google_cloud.dart';
import 'package:shelf/shelf.dart';

Future<void> main() async {
  final handler = const Pipeline()
      .addMiddleware(createLoggingMiddleware())
      .addHandler(_helloWorldHandler);

  await serveHandler(handler);
}

Response _helloWorldHandler(Request request) {
  return Response.ok('Hello, World!');
}

Classes

RequestLogger
Allows logging at a specified severity.

Properties

badRequestMiddleware → Middleware
Adds logic which catches BadRequestException, logs details to stderr and returns a corresponding Response.
no setter
currentLogger RequestLogger
Returns the current RequestLogger.
no setter

Functions

cloudLoggingMiddleware(String projectId) → Middleware
Return Middleware that logs errors using Google Cloud structured logs and returns the correct response.
createLoggingMiddleware({String? projectId}) → Middleware
Convenience Middleware that handles logging depending on projectId.
listenPortFromEnvironment() int
Returns the port to listen on from environment variable or uses the default 8080.
serveHandler(Handler handler) Future<void>
Serves handler on InternetAddress.anyIPv4 using the port returned by listenPortFromEnvironment.
waitForTerminate() Future<void>
Returns a Future that completes when the process receives a ProcessSignal requesting a shutdown.

Exceptions / Errors

BadConfigurationException
Thrown if a service is configured incorrectly.
BadRequestException
When thrown in a Handler, configured with badRequestMiddleware or similar, causes a response with statusCode to be returned.