api.go
Overview
The [api.go](/projects/291/69232) file defines the HTTP API layer for the Cosmos blockchain service within the application. It provides RESTful endpoints and WebSocket support to interact with Cosmos blockchain data such as account information, transaction history, transaction submission, and gas estimation.
The core component is the `API` struct, which acts as an HTTP handler integrating with a `RouteHandler` (business logic interface) and a WebSocket connection manager. The file manages incoming HTTP requests, upgrades connections to WebSockets when required, validates query parameters, and formats responses or errors consistently.
Key features include:
Starting and gracefully shutting down the HTTP server and WebSocket manager.
Serving blockchain info, accounts, transaction details, and transaction history.
Accepting raw transactions for broadcasting and estimating gas costs.
Validating paging parameters for paginated endpoints to prevent invalid or oversized queries.
WebSocket connection upgrade and lifecycle management.
This file is a crucial bridge between the client-facing API and the internal blockchain processing logic.
Detailed Descriptions
Constants and Variables
Name | Description |
|---|---|
`GRACEFUL_SHUTDOWN` | Duration (15s) to wait for graceful server shutdown. |
Default page size for validators endpoint (not used in this file). | |
Default page size when fetching transaction history (10). | |
Maximum allowed page size for transaction history queries (100). | |
`upgrader` | WebSocket upgrader from Gorilla WebSocket with buffer size and origin check. |
Type: API
The `API` struct encapsulates the HTTP API handler for Cosmos blockchain endpoints.
Fields:
Field | Type | Description |
|---|---|---|
`handler` | `RouteHandler` | Interface to blockchain business logic and data access. |
`manager` | `*websocket.Manager` | Manages WebSocket connections and message routing. |
`server` | `*http.Server` | HTTP server serving incoming API requests. |
Functions and Methods
New(handler RouteHandler, manager *websocket.Manager, server *http.Server) *API
Constructor function to create a new `API` instance.
Parameters:
handler: The route handler implementing blockchain logic.manager: WebSocket manager instance.server: HTTP server instance.
Returns:
Pointer to a new
APIstruct.
Usage:
api := New(myHandler, myWebSocketManager, myHTTPServer)
(a *API) Serve(errChan chan<- error)
Starts serving the API by launching the WebSocket and HTTP server.
Parameters:
errChan: Channel to send errors encountered while serving.
Behavior:
Logs server start.
Starts the WebSocket handler.
Starts the WebSocket manager in a goroutine.
Listens and serves HTTP requests.
Sends wrapped errors on
errChanif any failures occur.
Example:
errChan := make(chan error) go api.Serve(errChan)
(a *API) Shutdown()
Gracefully shuts down the HTTP server and stops WebSocket connections.
Behavior:
Creates a context with a 15-second timeout for shutdown.
Stops WebSocket handler.
Calls
Shutdownon the HTTP server.Logs any errors during shutdown.
(a *API) Root(w http.ResponseWriter, r *http.Request)
Root endpoint handler.
Behavior:
If the HTTP request contains an
Upgrade: websocketheader, upgrades the connection to WebSocket.Otherwise, redirects to API documentation.
Example:
GET / Upgrade: websocket
(a *API) ValidatePagingParams(w http.ResponseWriter, r *http.Request, defaultPageSize int, maxPageSize *int) (string, int, error)
Validates and parses paging query parameters `cursor` and `pageSize`.
Parameters:
w: HTTP response writer (used to write errors).r: HTTP request.defaultPageSize: Default page size if none provided.maxPageSize: Optional max page size limit.
Returns:
cursorstring from query (used for pagination).pageSizeinteger page size.errorif validation fails.
Validation Logic:
Defaults
pageSizetodefaultPageSizeif empty.Returns error if
pageSizeis zero or exceedsmaxPageSize.Returns error if
pageSizeis not an integer.
Usage Example:
cursor, pageSize, err := api.ValidatePagingParams(w, r, 10, &maxPageSize)
(a *API) Websocket(w http.ResponseWriter, r *http.Request)
Handles upgrading an HTTP connection to WebSocket and managing the new connection.
Behavior:
Uses Gorilla WebSocket upgrader to upgrade the connection.
On success, registers new WebSocket connection via the route handler.
On failure, returns HTTP 500 with error.
(a *API) Info(w http.ResponseWriter, r *http.Request)
Returns general blockchain node information.
Behavior:
Calls
GetInfo()on the route handler.Writes JSON response or error.
(a *API) Account(w http.ResponseWriter, r *http.Request)
Returns account details for a given public key.
Parameters:
Expects
pubkeyURL variable (validated by middleware).
Behavior:
Calls
GetAccount(pubkey)on the route handler.Writes JSON response or error.
(a *API) TxHistory(w http.ResponseWriter, r *http.Request)
Returns a paginated list of transactions for a given public key.
Parameters:
pubkeyURL variable.Paging query parameters:
cursorandpageSize.
Behavior:
Validates paging parameters with max page size limit.
Calls
GetTxHistory(pubkey, cursor, pageSize)on the route handler.Writes JSON response or error.
(a *API) Tx(w http.ResponseWriter, r *http.Request)
Returns details for a specific transaction by transaction ID.
Parameters:
txidURL variable.
Behavior:
Validates presence of
txid.Calls
GetTx(txid)on the route handler.Writes JSON response or error.
(a *API) SendTx(w http.ResponseWriter, r *http.Request)
Submits a raw transaction to the blockchain network.
Request Body:
JSON object matching
api.TxBodycontainingRawTxstring.
Behavior:
Decodes JSON request body.
Calls
SendTx(rawTx)on the route handler.Returns transaction hash or error.
(a *API) EstimateGas(w http.ResponseWriter, r *http.Request)
Estimates the gas fee required for a raw transaction.
Request Body:
JSON object matching
api.TxBodycontainingRawTxstring.
Behavior:
Decodes JSON request body.
Calls
EstimateGas(rawTx)on the route handler.Returns estimated gas or error.
Important Implementation Details
WebSocket Handling:
The file uses Gorilla WebSocket's upgrader with a permissive origin check (CheckOriginalways returnstrue) to allow WebSocket connections from any origin. The WebSocket lifecycle (connection creation, message handling) is delegated to theRouteHandlerandwebsocket.Manager.Paging Validation:
TheValidatePagingParamsmethod ensures thatpageSizequery parameter is numeric, within allowed bounds, and never zero, preventing excessive or invalid queries to the backend.Error Handling:
All API handlers use centralized error and response helpers from the importedapipackage (api.HandleErrorandapi.HandleResponse) to maintain consistent HTTP status codes and JSON response structure.Graceful Shutdown:
Shutdown()uses a 15-second timeout context to allow the HTTP server to finish processing current requests before closing.
Interaction with Other Parts of the System
RouteHandler:
Thehandlerfield is an interface responsible for the core blockchain logic such as fetching accounts, transactions, and sending transactions. This abstraction allows the API layer to remain decoupled from blockchain-specific implementations.websocket.Manager:
Manages WebSocket connections, including broadcasting and lifecycle, running concurrently viamanager.Start().HTTP Server:
The configuredhttp.Serverlistens on the specified port and delegates incoming HTTP requests to theAPIhandlers.API Utilities (
apipackage):
Provides common utilities for error handling, response formatting, and API documentation redirection.Router (
mux):
Uses Gorilla Mux to parse URL variables such aspubkeyandtxid.
Visual Diagram
classDiagram
class API {
-handler: RouteHandler
-manager: *websocket.Manager
-server: *http.Server
+New(handler, manager, server) *API
+Serve(errChan chan<- error)
+Shutdown()
+Root(w http.ResponseWriter, r *http.Request)
+ValidatePagingParams(w http.ResponseWriter, r *http.Request, defaultPageSize int, maxPageSize *int) (string, int, error)
+Websocket(w http.ResponseWriter, r *http.Request)
+Info(w http.ResponseWriter, r *http.Request)
+Account(w http.ResponseWriter, r *http.Request)
+TxHistory(w http.ResponseWriter, r *http.Request)
+Tx(w http.ResponseWriter, r *http.Request)
+SendTx(w http.ResponseWriter, r *http.Request)
+EstimateGas(w http.ResponseWriter, r *http.Request)
}
API --> RouteHandler : uses
API --> websocket.Manager : manages
API --> http.Server : serves
API ..> api.HandleError : uses utility
API ..> api.HandleResponse : uses utility
Summary
The [api.go](/projects/291/69232) file implements the HTTP API for Cosmos blockchain interactions, providing endpoints for querying blockchain data, managing transactions, and supporting WebSocket connections. It is designed with clean separation of concerns, delegating business logic to a `RouteHandler` interface, and maintaining consistent request validation, error handling, and graceful server lifecycle management. This file integrates tightly with the WebSocket manager and HTTP server to deliver a responsive, scalable API service.