DEV Community

tengxgfyrz67s
tengxgfyrz67s

Posted on

Getting Started with Hyperlane

Project Code:https://github.com/hyperlane-dev/hyperlane

Introduction

Hyperlane is a lightweight, high-performance, cross-platform Rust HTTP server library built on top of Tokio. It provides a powerful and flexible foundation for building web applications and APIs with Rust. Whether you're creating a simple REST API or a complex web service, Hyperlane offers the tools and performance you need to get the job done efficiently.

What sets Hyperlane apart is its focus on developer productivity without sacrificing performance. The library provides two complementary APIs: a straightforward programmatic API and a derive macro-based API that reduces boilerplate code. This dual approach means you can choose the style that best fits your project and coding preferences.

Key Features

Hyperlane comes packed with features that make it an excellent choice for Rust web development:

  • Lightweight and Fast: Built on Tokio's async runtime, Hyperlane delivers exceptional performance. In benchmark tests with Keep-Alive disabled, Hyperlane achieves 51,031 QPS, outperforming Tokio (49,555), Rocket (49,345), and Gin (40,149).
  • Cross-Platform: Works seamlessly across different operating systems.
  • Middleware System: A flexible middleware architecture for request and response processing.
  • Attribute Macros: Derive macros that eliminate boilerplate and make your code more declarative.
  • WebSocket Support: Built-in WebSocket upgrade handling.
  • SSE (Server-Sent Events): Native support for streaming events to clients.
  • Flexible Routing: Static routes, dynamic path parameters, and regex-based routing.
  • Cookie Management: Full cookie support with a builder pattern.
  • Graceful Shutdown: Clean server shutdown capabilities.
  • Multi-Server Support: Run multiple server instances concurrently.

Performance Benchmarks

Hyperlane's performance has been rigorously tested against popular frameworks:

Framework Keep-Alive Off (QPS) Keep-Alive On (QPS)
Hyperlane 51,031 334,888
Tokio 49,555 340,130
Rocket 49,345 298,945
Gin 40,149 242,570

In an ab test with 1 million requests (Keep-Alive enabled), Hyperlane achieved 316,211 QPS, demonstrating its ability to handle massive workloads efficiently.

Installation

Getting started with Hyperlane is straightforward. Add it to your Rust project using Cargo:

cargo add hyperlane
Enter fullscreen mode Exit fullscreen mode

This command adds Hyperlane as a dependency to your Cargo.toml file. Make sure you have the Tokio runtime available in your project, as Hyperlane builds on top of it.

Your First Server

Let's create a simple HTTP server to understand the basics. Here's the minimal code needed to get a server up and running:

#[tokio::main]
async fn main() {
    let mut server: Server = Server::default();
    let server_control_hook: ServerControlHook = server.run().await.unwrap_or_default();
    server_control_hook.wait().await;
}
Enter fullscreen mode Exit fullscreen mode

That's it! With just a few lines of code, you have a fully functional HTTP server. Let's break down what each line does:

  1. #[tokio::main] - This attribute macro sets up the Tokio async runtime, which Hyperlane relies on for handling concurrent connections.
  2. Server::default() - Creates a new server instance with default configuration (listening on 127.0.0.1:80).
  3. server.run().await - Starts the server asynchronously and returns a ServerControlHook.
  4. server_control_hook.wait().await - Keeps the server running until it's explicitly shut down.

Server Creation Options

Hyperlane provides multiple ways to create a server, giving you flexibility in how you configure your application:

Default Server

The simplest approach uses default settings:

let mut server: Server = Server::default();
let server_control_hook: ServerControlHook = server.run().await.unwrap_or_default();
server_control_hook.wait().await;
Enter fullscreen mode Exit fullscreen mode

From ServerConfig

For more control, create a server from a ServerConfig:

let server_config: ServerConfig = ServerConfig::default();
let mut server: Server = Server::from(server_config);
Enter fullscreen mode Exit fullscreen mode

From RequestConfig

You can also create a server from a RequestConfig:

let request_config: RequestConfig = RequestConfig::default();
let mut server: Server = Server::from(request_config);
Enter fullscreen mode Exit fullscreen mode

Attribute Macro Style

Hyperlane supports a declarative programming style using attribute macros. This approach can make your code more concise and expressive:

use hyperlane::*;
use hyperlane_macros::*;

#[hyperlane(server: Server)]
#[hyperlane(server_config: ServerConfig)]
#[tokio::main]
async fn main() {
    server_config.set_nodelay(Some(false));
    server.server_config(server_config);
    let server_control_hook: ServerControlHook = server.run().await.unwrap_or_default();
    server_control_hook.wait().await;
}
Enter fullscreen mode Exit fullscreen mode

In this style, the #[hyperlane(server: Server)] and #[hyperlane(server_config: ServerConfig)] macros automatically inject the server and server_config variables into your main function. You can then configure the server directly before running it.

Project Structure

For larger Hyperlane projects, a well-organized directory structure helps maintain code quality:

├── application/controller/domain/exception/mapper/middleware/model/repository/service/utils/view
├── bootstrap/application/framework
├── config/application/framework
├── plugin/database/env/logger/mysql/postgresql/process/redis
├── resources/docker/env/sql/static/templates
Enter fullscreen mode Exit fullscreen mode

This structure separates concerns into logical layers:

  • application/: Contains your application logic, including controllers, domain models, services, and middleware.
  • bootstrap/: Application bootstrapping and initialization code.
  • config/: Configuration management.
  • plugin/: Plugin integrations for databases, logging, and other external services.
  • resources/: Static assets, templates, Docker configurations, and SQL files.

Recommended Tools

The Hyperlane ecosystem includes several useful companion tools:

  • hyperlane-utils: Utility functions for Hyperlane applications
  • hyperlane-log: Logging support
  • hyperlane-time: Time utilities
  • hyperlane-broadcast: Broadcasting capabilities
  • hyperlane-plugin-websocket: Enhanced WebSocket plugin
  • utoipa: OpenAPI documentation support
  • http-request: HTTP request utilities
  • server-manager: Server management tools
  • urlencoding: URL encoding/decoding
  • chunkify: Data chunking utilities

Next Steps

Now that you have a basic understanding of Hyperlane, you're ready to explore more advanced topics:

  • Server Configuration: Learn how to fine-tune server settings like address, nodelay, and TTL.
  • Middleware System: Understand how to intercept and process requests and responses.
  • Routing: Set up URL routing with static, dynamic, and regex-based routes.
  • Request Handling: Extract data from incoming requests including headers, query parameters, and body content.
  • Response Building: Construct and send HTTP responses with proper status codes and headers.

Each of these topics is covered in detail in the following articles in this series.

Conclusion

Hyperlane provides a solid foundation for building high-performance web applications in Rust. Its combination of a simple API, powerful attribute macros, and excellent performance makes it an attractive choice for developers looking to build web services. With just a few lines of code, you can have a production-ready HTTP server running, and the flexible architecture allows you to scale from simple APIs to complex web applications.

In the next article, we'll dive deeper into server configuration, exploring how to customize your Hyperlane server for optimal performance and functionality.


Project Code:https://github.com/hyperlane-dev/hyperlane

Top comments (0)