fix: API JSON error responses + navbar with dropdowns
- Add backend/libs/go-http-errors for consistent JSON errors - REST API: use writeMethodNotAllowed, writeNotFound, writeInternalError - middleware, gateway, search: use httperrors.WriteJSON - SPA: navbar with Explore/Tools/More dropdowns, initNavDropdowns() - Next.js: Navbar component with dropdowns + mobile menu Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -6,6 +6,8 @@ import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
|
||||
httperrors "github.com/explorer/backend/libs/go-http-errors"
|
||||
)
|
||||
|
||||
// Gateway represents the API gateway
|
||||
@@ -51,13 +53,13 @@ func (g *Gateway) handleRequest(proxy *httputil.ReverseProxy) http.HandlerFunc {
|
||||
|
||||
// Authentication
|
||||
if !g.auth.Authenticate(r) {
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
httperrors.WriteJSON(w, http.StatusUnauthorized, "UNAUTHORIZED", "Unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
// Rate limiting
|
||||
if !g.rateLimiter.Allow(r) {
|
||||
http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
|
||||
httperrors.WriteJSON(w, http.StatusTooManyRequests, "RATE_LIMIT_EXCEEDED", "Rate limit exceeded")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@ package middleware
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
httperrors "github.com/explorer/backend/libs/go-http-errors"
|
||||
)
|
||||
|
||||
// SecurityMiddleware adds security headers
|
||||
@@ -52,7 +54,7 @@ func (m *SecurityMiddleware) BlockWriteCalls(next http.Handler) http.Handler {
|
||||
if !strings.Contains(path, "weth") && !strings.Contains(path, "wrap") && !strings.Contains(path, "unwrap") {
|
||||
// Block other write operations for Track 1
|
||||
if strings.HasPrefix(path, "/api/v1/track1") {
|
||||
http.Error(w, "Write operations not allowed for Track 1 (public)", http.StatusForbidden)
|
||||
httperrors.WriteJSON(w, http.StatusForbidden, "FORBIDDEN", "Write operations not allowed for Track 1 (public)")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,20 +12,20 @@ import (
|
||||
// handleGetAddress handles GET /api/v1/addresses/{chain_id}/{address}
|
||||
func (s *Server) handleGetAddress(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
writeMethodNotAllowed(w)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse address from URL
|
||||
address := r.URL.Query().Get("address")
|
||||
if address == "" {
|
||||
http.Error(w, "Address required", http.StatusBadRequest)
|
||||
writeValidationError(w, fmt.Errorf("address required"))
|
||||
return
|
||||
}
|
||||
|
||||
// Validate address format
|
||||
if !isValidAddress(address) {
|
||||
http.Error(w, "Invalid address format", http.StatusBadRequest)
|
||||
writeValidationError(w, ErrInvalidAddress)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ func (s *Server) handleGetAddress(w http.ResponseWriter, r *http.Request) {
|
||||
s.chainID, address,
|
||||
).Scan(&txCount)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Database error: %v", err), http.StatusInternalServerError)
|
||||
writeInternalError(w, "Database error")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ var dualChainTokenListJSON []byte
|
||||
func (s *Server) handleConfigNetworks(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.Header().Set("Allow", "GET")
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
writeMethodNotAllowed(w)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
@@ -27,7 +27,7 @@ func (s *Server) handleConfigNetworks(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) handleConfigTokenList(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.Header().Set("Allow", "GET")
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
writeMethodNotAllowed(w)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
@@ -49,3 +49,8 @@ func writeForbidden(w http.ResponseWriter) {
|
||||
writeError(w, http.StatusForbidden, "FORBIDDEN", "Access denied")
|
||||
}
|
||||
|
||||
// writeMethodNotAllowed writes a 405 error response (JSON)
|
||||
func writeMethodNotAllowed(w http.ResponseWriter) {
|
||||
writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Method not allowed")
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,10 @@ import (
|
||||
// This provides Etherscan-compatible API endpoints
|
||||
func (s *Server) handleEtherscanAPI(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
writeMethodNotAllowed(w)
|
||||
return
|
||||
}
|
||||
if !s.requireDB(w) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,10 @@ import (
|
||||
// handleSearch handles GET /api/v1/search
|
||||
func (s *Server) handleSearch(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
writeMethodNotAllowed(w)
|
||||
return
|
||||
}
|
||||
if !s.requireDB(w) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/explorer/backend/auth"
|
||||
"github.com/explorer/backend/api/middleware"
|
||||
httpmiddleware "github.com/explorer/backend/libs/go-http-middleware"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
@@ -54,8 +55,12 @@ func (s *Server) Start(port int) error {
|
||||
// Setup track routes with proper middleware
|
||||
s.SetupTrackRoutes(mux, authMiddleware)
|
||||
|
||||
// Initialize security middleware
|
||||
securityMiddleware := middleware.NewSecurityMiddleware()
|
||||
// Security headers (reusable lib; CSP from env or explorer default)
|
||||
csp := os.Getenv("CSP_HEADER")
|
||||
if csp == "" {
|
||||
csp = "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://unpkg.com https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; font-src 'self' https://cdnjs.cloudflare.com; img-src 'self' data: https:; connect-src 'self' https://explorer.d-bis.org https://rpc-http-pub.d-bis.org wss://rpc-ws-pub.d-bis.org http://192.168.11.221:8545 ws://192.168.11.221:8546;"
|
||||
}
|
||||
securityMiddleware := httpmiddleware.NewSecurity(csp)
|
||||
|
||||
// Add middleware for all routes (outermost to innermost)
|
||||
handler := securityMiddleware.AddSecurityHeaders(
|
||||
@@ -82,9 +87,13 @@ func (s *Server) addMiddleware(next http.Handler) http.Handler {
|
||||
w.Header().Set("X-Explorer-Version", "1.0.0")
|
||||
w.Header().Set("X-Powered-By", "SolaceScanScout")
|
||||
|
||||
// Add CORS headers for API routes
|
||||
// Add CORS headers for API routes (optional: set CORS_ALLOWED_ORIGIN to restrict, e.g. https://explorer.d-bis.org)
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
origin := os.Getenv("CORS_ALLOWED_ORIGIN")
|
||||
if origin == "" {
|
||||
origin = "*"
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-API-Key")
|
||||
|
||||
@@ -99,10 +108,22 @@ func (s *Server) addMiddleware(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
// requireDB returns false and writes 503 if db is nil (e.g. in tests without DB)
|
||||
func (s *Server) requireDB(w http.ResponseWriter) bool {
|
||||
if s.db == nil {
|
||||
writeError(w, http.StatusServiceUnavailable, "service_unavailable", "database unavailable")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// handleListBlocks handles GET /api/v1/blocks
|
||||
func (s *Server) handleListBlocks(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
writeMethodNotAllowed(w)
|
||||
return
|
||||
}
|
||||
if !s.requireDB(w) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -132,7 +153,7 @@ func (s *Server) handleListBlocks(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
rows, err := s.db.Query(ctx, query, s.chainID, pageSize, offset)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Database error: %v", err), http.StatusInternalServerError)
|
||||
writeInternalError(w, "Database error")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
@@ -191,12 +212,15 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Explorer-Version", "1.0.0")
|
||||
|
||||
// Check database connection
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
dbStatus := "ok"
|
||||
if err := s.db.Ping(ctx); err != nil {
|
||||
dbStatus = "error: " + err.Error()
|
||||
if s.db != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := s.db.Ping(ctx); err != nil {
|
||||
dbStatus = "error: " + err.Error()
|
||||
}
|
||||
} else {
|
||||
dbStatus = "unavailable"
|
||||
}
|
||||
|
||||
health := map[string]interface{}{
|
||||
|
||||
@@ -10,7 +10,10 @@ import (
|
||||
// handleStats handles GET /api/v2/stats
|
||||
func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
writeMethodNotAllowed(w)
|
||||
return
|
||||
}
|
||||
if !s.requireDB(w) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,10 @@ import (
|
||||
// handleListTransactions handles GET /api/v1/transactions
|
||||
func (s *Server) handleListTransactions(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
writeMethodNotAllowed(w)
|
||||
return
|
||||
}
|
||||
if !s.requireDB(w) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -70,7 +73,7 @@ func (s *Server) handleListTransactions(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
rows, err := s.db.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Database error: %v", err), http.StatusInternalServerError)
|
||||
writeInternalError(w, "Database error")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
@@ -178,7 +181,7 @@ func (s *Server) handleGetTransactionByHash(w http.ResponseWriter, r *http.Reque
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Transaction not found: %v", err), http.StatusNotFound)
|
||||
writeNotFound(w, "Transaction")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
"github.com/elastic/go-elasticsearch/v8"
|
||||
"github.com/elastic/go-elasticsearch/v8/esapi"
|
||||
httperrors "github.com/explorer/backend/libs/go-http-errors"
|
||||
)
|
||||
|
||||
// SearchService handles unified search
|
||||
@@ -131,13 +132,13 @@ func (s *SearchService) parseResult(source map[string]interface{}) SearchResult
|
||||
// HandleSearch handles HTTP search requests
|
||||
func (s *SearchService) HandleSearch(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
httperrors.WriteJSON(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
query := r.URL.Query().Get("q")
|
||||
if query == "" {
|
||||
http.Error(w, "Query parameter 'q' is required", http.StatusBadRequest)
|
||||
httperrors.WriteJSON(w, http.StatusBadRequest, "BAD_REQUEST", "Query parameter 'q' is required")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -157,7 +158,7 @@ func (s *SearchService) HandleSearch(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
results, err := s.Search(r.Context(), query, chainID, limit)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Search failed: %v", err), http.StatusInternalServerError)
|
||||
httperrors.WriteJSON(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Search failed")
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
26
backend/libs/go-http-errors/errors.go
Normal file
26
backend/libs/go-http-errors/errors.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package httperrors
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ErrorResponse is the standard JSON error body for API responses.
|
||||
type ErrorResponse struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
// WriteJSON writes a JSON error response with the given status code and message.
|
||||
func WriteJSON(w http.ResponseWriter, statusCode int, code, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(statusCode)
|
||||
json.NewEncoder(w).Encode(ErrorResponse{
|
||||
Error: struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}{Code: code, Message: message},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user