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:
defiQUG
2026-02-16 03:09:53 -08:00
parent 01e126a868
commit a53c15507f
16 changed files with 3979 additions and 3191 deletions

View File

@@ -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
}

View File

@@ -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
}
}

View File

@@ -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
}

View File

@@ -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")

View File

@@ -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")
}

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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{}{

View File

@@ -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
}

View File

@@ -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
}

View File

@@ -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
}

View 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},
})
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import Link from 'next/link'
import Navbar from '@/components/common/Navbar'
import './globals.css'
const inter = Inter({ subsets: ['latin'] })
@@ -18,34 +18,7 @@ export default function RootLayout({
return (
<html lang="en">
<body className={inter.className}>
<nav className="bg-white dark:bg-gray-800 shadow-sm border-b border-gray-200 dark:border-gray-700">
<div className="container mx-auto px-4">
<div className="flex items-center justify-between h-16">
<div className="flex items-center gap-8">
<Link href="/" className="text-xl font-bold text-primary-600">
<div className="flex flex-col">
<span>SolaceScanScout</span>
<span className="text-xs font-normal text-gray-500">The Defi Oracle Meta Explorer</span>
</div>
</Link>
<div className="flex gap-4">
<Link href="/blocks" className="text-gray-700 dark:text-gray-300 hover:text-primary-600">
Blocks
</Link>
<Link href="/transactions" className="text-gray-700 dark:text-gray-300 hover:text-primary-600">
Transactions
</Link>
<Link href="/search" className="text-gray-700 dark:text-gray-300 hover:text-primary-600">
Search
</Link>
<Link href="/wallet" className="text-gray-700 dark:text-gray-300 hover:text-primary-600">
Wallet
</Link>
</div>
</div>
</div>
</div>
</nav>
<Navbar />
<main>{children}</main>
</body>
</html>

View File

@@ -0,0 +1,166 @@
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { useState } from 'react'
const navLink = 'text-gray-700 dark:text-gray-300 hover:text-primary-600 dark:hover:text-primary-400 transition-colors'
const navLinkActive = 'text-primary-600 dark:text-primary-400 font-medium'
function NavDropdown({
label,
icon,
children,
}: {
label: string
icon: React.ReactNode
children: React.ReactNode
}) {
const [open, setOpen] = useState(false)
return (
<div
className="relative"
onMouseEnter={() => setOpen(true)}
onMouseLeave={() => setOpen(false)}
>
<button
type="button"
className={`flex items-center gap-1.5 px-3 py-2 rounded-md ${navLink}`}
onClick={() => setOpen((v) => !v)}
aria-expanded={open}
aria-haspopup="true"
>
{icon}
<span>{label}</span>
<svg className={`w-3.5 h-3.5 transition-transform ${open ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
{open && (
<ul
className="absolute left-0 top-full mt-1 min-w-[200px] rounded-lg bg-white dark:bg-gray-800 shadow-lg border border-gray-200 dark:border-gray-700 py-1 z-50"
role="menu"
>
{children}
</ul>
)}
</div>
)
}
function DropdownItem({
href,
icon,
children,
external,
}: {
href: string
icon?: React.ReactNode
children: React.ReactNode
external?: boolean
}) {
const className = `flex items-center gap-2 px-4 py-2.5 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-primary-600 dark:hover:text-primary-400 ${navLink}`
if (external) {
return (
<li role="none">
<a href={href} target="_self" rel="noopener" className={className} role="menuitem">
{icon}
<span>{children}</span>
</a>
</li>
)
}
return (
<li role="none">
<Link href={href} className={className} role="menuitem">
{icon}
<span>{children}</span>
</Link>
</li>
)
}
export default function Navbar() {
const pathname = usePathname() ?? ''
const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
const [exploreOpen, setExploreOpen] = useState(false)
const [toolsOpen, setToolsOpen] = useState(false)
return (
<nav className="bg-white dark:bg-gray-800 shadow-sm border-b border-gray-200 dark:border-gray-700">
<div className="container mx-auto px-4">
<div className="flex items-center justify-between h-16">
<div className="flex items-center gap-4 md:gap-8">
<Link href="/" className="text-xl font-bold text-primary-600 dark:text-primary-400 flex flex-col" onClick={() => setMobileMenuOpen(false)}>
<span>SolaceScanScout</span>
<span className="text-xs font-normal text-gray-500 dark:text-gray-400">The Defi Oracle Meta Explorer</span>
</Link>
<div className="hidden md:flex items-center gap-1">
<NavDropdown
label="Explore"
icon={<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0h.5a2.5 2.5 0 002.5-2.5V3.935M12 12a2 2 0 104 0 2 2 0 00-4 0z" /></svg>}
>
<DropdownItem href="/" icon={<span className="text-gray-400"></span>}>Home</DropdownItem>
<DropdownItem href="/blocks" icon={<span className="text-gray-400"></span>}>Blocks</DropdownItem>
<DropdownItem href="/transactions" icon={<span className="text-gray-400"></span>}>Transactions</DropdownItem>
</NavDropdown>
<NavDropdown
label="Tools"
icon={<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" /><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /></svg>}
>
<DropdownItem href="/search">Search</DropdownItem>
<DropdownItem href="/wallet">Wallet</DropdownItem>
</NavDropdown>
</div>
</div>
<div className="flex items-center md:hidden">
<button
type="button"
className="p-2 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
onClick={() => setMobileMenuOpen((o) => !o)}
aria-expanded={mobileMenuOpen}
aria-label="Toggle menu"
>
{mobileMenuOpen ? (
<svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
) : (
<svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" /></svg>
)}
</button>
</div>
</div>
{mobileMenuOpen && (
<div className="md:hidden py-3 border-t border-gray-200 dark:border-gray-700">
<div className="flex flex-col gap-1">
<Link href="/" className={`px-3 py-2.5 rounded-md ${pathname === '/' ? navLinkActive : navLink}`} onClick={() => setMobileMenuOpen(false)}>Home</Link>
<div className="relative">
<button type="button" className={`flex items-center justify-between w-full px-3 py-2.5 rounded-md ${navLink}`} onClick={() => setExploreOpen((o) => !o)} aria-expanded={exploreOpen}>
<span>Explore</span>
<svg className={`w-4 h-4 transition-transform ${exploreOpen ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
</button>
{exploreOpen && (
<ul className="pl-4 mt-1 space-y-0.5">
<li><Link href="/blocks" className={`block px-3 py-2 rounded-md ${navLink}`} onClick={() => setMobileMenuOpen(false)}>Blocks</Link></li>
<li><Link href="/transactions" className={`block px-3 py-2 rounded-md ${navLink}`} onClick={() => setMobileMenuOpen(false)}>Transactions</Link></li>
</ul>
)}
</div>
<div className="relative">
<button type="button" className={`flex items-center justify-between w-full px-3 py-2.5 rounded-md ${navLink}`} onClick={() => setToolsOpen((o) => !o)} aria-expanded={toolsOpen}>
<span>Tools</span>
<svg className={`w-4 h-4 transition-transform ${toolsOpen ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
</button>
{toolsOpen && (
<ul className="pl-4 mt-1 space-y-0.5">
<li><Link href="/search" className={`block px-3 py-2 rounded-md ${navLink}`} onClick={() => setMobileMenuOpen(false)}>Search</Link></li>
<li><Link href="/wallet" className={`block px-3 py-2 rounded-md ${navLink}`} onClick={() => setMobileMenuOpen(false)}>Wallet</Link></li>
</ul>
)}
</div>
</div>
</div>
)}
</div>
</nav>
)
}