middleware.go
Overview
The [middleware.go](/projects/291/69263) file defines HTTP middleware functions intended for validating public keys (`pubkey`) within incoming HTTP requests in a Cosmos blockchain-related API service. These middleware functions intercept requests and ensure that the `pubkey` parameter is present and valid before allowing the request to proceed to the next handler. This validation step helps enforce data integrity and prevents unnecessary processing of invalid requests.
Specifically, the file provides two middleware functions:
ValidatePubkey: Validates a general public key.ValidateValidatorPubkey: Validates a validator-specific public key.
Both middleware functions leverage validation helper functions (assumed to be implemented elsewhere in the codebase) to check the format and correctness of the `pubkey`.
Detailed Descriptions
Functions
ValidatePubkey
func ValidatePubkey(next http.Handler) http.Handler
**Description:** Middleware function that validates the presence and correctness of a general public key (`pubkey`) extracted from the request URL variables. If validation passes, the middleware forwards the request to the next handler; otherwise, it returns an HTTP 400 Bad Request error with an appropriate message.
**Parameters:**
next http.Handler: The next HTTP handler in the chain to be called if validation succeeds.
**Returns:**
http.Handler: A wrapped HTTP handler that performs validation before callingnext.
**Behavior:**
Extracts the
pubkeyparameter from the URL path variables using themuxrouter.Checks if
pubkeyis present and not empty.Validates the
pubkeyformat using the helper functionIsValidAddress(pubkey).If validation fails, responds with HTTP 400 and an error message using
api.HandleError.If validation succeeds, calls the
nexthandler.
**Usage Example:**
router := mux.NewRouter()
router.Handle("/accounts/{pubkey}", ValidatePubkey(accountHandler))
In this example, the middleware ensures that requests to `/accounts/{pubkey}` contain a valid public key before `accountHandler` executes.
ValidateValidatorPubkey
func ValidateValidatorPubkey(next http.Handler) http.Handler
**Description:** Middleware function that validates the presence and correctness of a validator-specific public key (`pubkey`) extracted from the request URL variables. Similar to `ValidatePubkey`, but the validation is specific to validator addresses.
**Parameters:**
next http.Handler: The next HTTP handler in the chain to be called if validation succeeds.
**Returns:**
http.Handler: A wrapped HTTP handler that performs validator pubkey validation before callingnext.
**Behavior:**
Extracts the
pubkeyparameter from the URL path variables using themuxrouter.Checks if
pubkeyis present and not empty.Validates the
pubkeyformat using the helper functionIsValidValidatorAddress(pubkey).If validation fails, responds with HTTP 400 and an error message via
api.HandleError.If validation succeeds, calls the
nexthandler.
**Usage Example:**
router := mux.NewRouter()
router.Handle("/validators/{pubkey}", ValidateValidatorPubkey(validatorHandler))
Here, requests to `/validators/{pubkey}` require a valid validator public key before `validatorHandler` processes them.
Important Implementation Details
Dependency on
mux.Vars: Both middleware functions extract thepubkeyfrom URL path variables usingmux.Vars(r). This means the router must define routes with the{pubkey}variable to work correctly.Use of external validation helpers: The actual validation logic is delegated to two helper functions:
IsValidAddress(pubkey string) boolIsValidValidatorAddress(pubkey string) bool
These functions are assumed to check the format and validity of the public keys according to Cosmos blockchain standards but their implementation is outside this file.
Error Handling: Uses
api.HandleError(w, statusCode, message)to send HTTP error responses consistently.Middleware Pattern: These functions follow the standard Go HTTP middleware pattern, wrapping an
http.Handlerwith additional logic.
Interaction with Other Parts of the System
Router Setup: This middleware is designed to be integrated with Gorilla Mux routers that handle HTTP requests. It assumes routes contain a
{pubkey}parameter.Validation Functions: Relies on validation functions
IsValidAddressandIsValidValidatorAddress, expected to be implemented in the same package or imported accordingly.API Error Handling: Uses
api.HandleErrorfrom thegithub.com/shapeshift/unchained/pkg/apipackage to manage error responses uniformly.Subsequent Handlers: If validation passes, the request is delegated to the next handler, which processes the valid request (e.g., fetching account or validator data).
Visual Diagram: Middleware Flowchart
This flowchart represents the validation workflow of each middleware function as it handles incoming HTTP requests.
flowchart TD
A[Incoming HTTP Request] --> B{Extract "pubkey" from URL}
B -->|No "pubkey" found| E[Respond 400 Bad Request: "pubkey required"]
B -->|"pubkey" found| C{Validate "pubkey" format}
C -->|Invalid pubkey| F[Respond 400 Bad Request: "invalid pubkey"]
C -->|Valid pubkey| D[Call next handler]
For `ValidateValidatorPubkey`, the "Validate `pubkey` format" step uses `IsValidValidatorAddress` instead of `IsValidAddress`.
Summary
The [middleware.go](/projects/291/69263) file provides essential middleware utilities for validating public keys in HTTP request paths within a Cosmos blockchain API context. These middleware functions help ensure that only requests with valid `pubkey` parameters are processed further, improving API robustness and reducing potential errors downstream. The modular middleware design integrates seamlessly with Gorilla Mux and enforces consistent validation and error handling practices across the API service.