Hertz Examples

repository·main·Indexed 43 days ago

https://github.com/cloudwego/hertz-examples

A comprehensive collection of practical examples for the Hertz web framework. Includes demonstrations for basic servers, microservices, and integrations with JWT, GORM, Redis, Thrift/Protobuf IDLs, and the jade template engine. Features complex business demos such as a TikTok-like application and implementations for request binding, validation, and distributed session management.

Tokens
91.9K
Snippets
343
Records
406
Agent score
55%

What's inside Hertz Examples

  1. Overview of hertz_session demo architecture

    main

    The hertz_session demo demonstrates a distributed session solution using hertz-contrib/sessions. This approach stores sessions in Redis (or a Redis cluster) to ensure session synchronization across multiple servers in a distributed system.

    Key technologies used in this demo:

    • Session Management: hertz-contrib/sessions for distributed sessions.
    • Security: hertz-contrib/csrf to prevent Cross-Site Request Forgery attacks.
    • Interface Definition: thrift IDL to define HTTP interfaces.
    • Code Generation: hz toolkit to generate Hertz code from IDL.
    • Database: Gorm with MySQL for data persistence.
    • Frontend: AdminLTE for login and registration pages.
  2. Overview of tiktok_demo services

    main

    The tiktok_demo is a Hertz server providing backend services for a TikTok-like application. It includes the following functional services:

    ServiceFunction
    userUser register / Get user information
    relationFollow / Get follow list / Get friend (mutual follow) list
    publishPublish video
    feedGet the last few of all videos as a feed stream
    favoriteLike the video
    commentComment on a video
    messageSend message with friends / Get message list with friends
  3. Overview of the hertz_gorm demo

    main

    The hertz_gorm project is a demonstration of integrating the Hertz web framework with Gorm (an ORM) and MySQL. It showcases a complete workflow including:

    • Defining HTTP interfaces using thrift IDL.
    • Generating code using the hz toolkit.
    • Implementing request binding and validation using Hertz features.
    • Performing database operations with Gorm and MySQL.
  4. Overview of hertz_swagger_gen example

    main

    The hertz_swagger_gen example demonstrates how to build a web service using Hertz with automated Swagger documentation generation.

    Key features demonstrated:

    • Defining HTTP interfaces using thrift IDL.
    • Generating code using the hz toolkit.
    • Integrating Gorm with MySQL for data persistence.
    • Using the thrift-gen-http-swagger plugin to automatically generate Swagger files and host a swagger ui service.

    Endpoints provided:

    • /swagger: Serves the Swagger documentation and the Swagger UI interface.
    • /handler: Contains core business logic for user operations: updating users, adding users, deleting users, and querying users.
  5. Overview of the Hz Template Project

    main

    The hz template is a scaffolding tool designed to generate a base project structure using the Hertz framework. It provides a standard MVC (Model-View-Controller) hierarchy and integrates several essential Hertz extensions and utilities.

    Key features include:

    • Hertz Framework Integration: Built on top of the Hertz web framework.
    • Pre-configured Extensions: Includes pprof, cors, recovery, access_log, and gzip.
    • Testing Support: Generates base code for unit tests.
    • Observability: Provides basic profiling functions.
    • Standardized Architecture: Implements a clean MVC code hierarchy.
  6. Learn how to implement a custom reverse proxy for Hertz

    main
    The reverseproxy examples directory provides several guides for implementing and customizing a reverse proxy using the Hertz framework. You can explore specific implementation patterns including standard usage, error handling, response modification, service discovery, and protocol support (TLS, SSE, WebSocket).
  7. Customizing Gzip compression in Hertz

    main

    Hertz supports Gzip compression middleware which can be customized to control which requests are compressed. You can configure the middleware using the following strategies:

    • Default compression: Uses standard compression settings.
    • Extension exclusion: Exclude specific file suffixes from being compressed (e.g., images or static assets).
    • Path exclusion: Exclude specific URL paths from being compressed.
    • Regex path exclusion: Use regular expressions to define complex path exclusion rules.
  8. Technologies used in hertz_jwt demo

    main

    The hertz_jwt demo demonstrates the integration of several components:

    • Hertz & JWT: Uses the hertz-contrib/jwt extension for login and authentication.
    • hz: Uses the hz code generation tool to scaffold the project.
    • Binding and Validate: Utilizes Hertz's built-in binding and validation features for request handling.
    • Gorm & MySQL: Uses the Gorm ORM to interact with a MySQL database.
  9. Learn about Hertz protocols

    main

    Hertz supports various communication protocols. You can find detailed guides for the following in the repository:

    • http1: Instructions on how to implement and use the HTTP/1.1 protocol.
    • tls: Instructions on how to use the TLS protocol and how to send TLS-encrypted requests using the Hertz client.

    For a complete list of supported protocols and advanced usage, refer to the official Hertz documentation at https://www.cloudwego.io/zh/docs/hertz/tutorials/basic-feature/protocol/.

  10. Use the Hertz Client

    main

    The Hertz client can be configured for various networking tasks:

    • Basic Requests: Send requests with support for deadlines, redirects, and timeouts (client/send_request).
    • Parameter Injection: Add query, form, path, and body parameters to requests (client/add_parameters).
    • File Operations: Upload files via the client (client/upload_file).
    • Streaming: Read streaming responses (client/streaming_read).
    • Proxying: Configure forward proxies for client requests (client/forward_proxy).
    • Middleware: Apply middleware to client-side requests (client/middleware).
  11. Explore Hertz Server features

    main

    The Server section of the examples covers core Hertz capabilities:

    Protocols & Connectivity

    • Basic: hello (Hello World), config (Server configuration).
    • Protocols: HTTP/1.1, TLS, HTTP/2, HTTP/3 (via extensions), and WebSocket (via extensions).
    • Streaming: Server-Sent Events (SSE) using the built-in SSE package, and request/response body streaming.

    Middleware & Security

    • Standard: BasicAuth, CORS, CSRF, Gzip, RequestID, and Recovery.
    • Advanced: Load balancing (custom algorithms), JWT, Casbin (authorization), Paseto, and KeyAuth.
    • Observability: pprof, Prometheus monitoring, OpenTelemetry (tracing Hertz-to-Kitex), and Sentry error reporting.
    • Performance: ETag, Cache (Memory/Redis), and Sentinel (traffic control).

    Request Handling & Data

    • Data Binding: Parameter binding, validation, and reading query/form/cookie parameters.
    • Response: Rendering JSON, HTML, Protobuf, Text, XML, and YAML.
    • Routing: Static, grouped, parameterized, and middleware-protected routes.
    • Files: File upload/download, static file serving, and template rendering.

    Advanced Server Patterns

    • Graceful Shutdown: Implementing clean server exits.
    • Testing: Unit testing handlers using ResponseRecord and PerformRequest (no network required).
    • Adaptors: Using standard library http.Handler within Hertz.
    • Reverse Proxy: Using the Hertz reverse proxy extension for proxying, TLS, discovery, and response modification.
  12. Configure Hertz Server-side features

    main

    Hertz provides extensive support for server-side operations. Key functional areas include:

    • Protocols: Support for HTTP/1.1, TLS, HTTP/2, HTTP/3 (QUIC), WebSocket, and SSE (Server-Sent Events).
    • Middleware: A wide range of built-in and community middleware including CORS, CSRF, BasicAuth, Gzip, RequestID, Recovery, JWT, Session (Cookie/Redis), Cache (Memory/Redis), and Casbin for authorization.
    • Request Handling: Parameter binding and validation, reading query/form/cookie parameters, file uploads/downloads, and streaming request/response bodies.
    • Response Rendering: Rendering JSON, HTML, Protobuf, Text, XML, and custom YAML.
    • Routing: Static routes, route groups, parameter routes, and middleware-attached routes.
    • Observability: Prometheus monitoring, OpenTelemetry tracing (to Kitex/Jaeger), and Sentry error reporting.
    • Advanced Server Features: Graceful shutdown, reverse proxy (with TLS, service discovery, and response modification), and Sentinel for flow control.