server

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Copyright © 2025 Semen Adamenko <semaadamenko1@gmail.com>

Copyright © 2025 Semen Adamenko <semaadamenko1@gmail.com>

Copyright © 2025 Semen Adamenko <semaadamenko1@gmail.com>

Copyright © 2025 Semen Adamenko <semaadamenko1@gmail.com>

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CORSMiddleware

func CORSMiddleware(next http.Handler) http.Handler

CORSMiddleware adds CORS headers to responses. In development, allows requests from localhost:3000 (Vite dev server). In production, uses same-origin so no CORS headers are needed.

func HandleWebSocket

func HandleWebSocket(hub *Hub) http.HandlerFunc

HandleWebSocket handles WebSocket connections

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a WebSocket client

type ConfigPayload

type ConfigPayload struct {
	URL         string   `json:"url"`
	Method      string   `json:"method"`
	Body        string   `json:"body,omitempty"`
	Headers     []string `json:"headers,omitempty"`
	Rate        string   `json:"rate"`
	Duration    string   `json:"duration"`
	Workers     uint     `json:"workers"`
	Connections uint     `json:"connections"`
}

ConfigPayload represents the test configuration

type ErrorBreakdownPayload

type ErrorBreakdownPayload struct {
	Timeout           uint64 `json:"timeout"`
	ConnectionRefused uint64 `json:"connection_refused"`
	DNS               uint64 `json:"dns"`
	TLS               uint64 `json:"tls"`
	Other             uint64 `json:"other"`
}

ErrorBreakdownPayload represents error type breakdown

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message"`
}

ErrorResponse represents an error response

type Handlers

type Handlers struct {
	// contains filtered or unexported fields
}

Handlers holds the HTTP handlers and dependencies

func NewHandlers

func NewHandlers(sm *SessionManager, hub *Hub) *Handlers

NewHandlers creates a new Handlers instance

func (*Handlers) HandleDownload

func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request)

HandleDownload handles GET /api/attack/results/download

func (*Handlers) HandleResults

func (h *Handlers) HandleResults(w http.ResponseWriter, r *http.Request)

HandleResults handles GET /api/attack/results

func (*Handlers) HandleStartAttack

func (h *Handlers) HandleStartAttack(w http.ResponseWriter, r *http.Request)

HandleStartAttack handles POST /api/attack/start

func (*Handlers) HandleStatus

func (h *Handlers) HandleStatus(w http.ResponseWriter, r *http.Request)

HandleStatus handles GET /api/attack/status

func (*Handlers) HandleStopAttack

func (h *Handlers) HandleStopAttack(w http.ResponseWriter, r *http.Request)

HandleStopAttack handles POST /api/attack/stop

type Hub

type Hub struct {
	// contains filtered or unexported fields
}

Hub manages WebSocket connections

func NewHub

func NewHub() *Hub

NewHub creates a new Hub

func (*Hub) Broadcast

func (h *Hub) Broadcast(msg WSMessage)

Broadcast sends a message to all connected clients

func (*Hub) ClientCount

func (h *Hub) ClientCount() int

ClientCount returns the number of connected clients

func (*Hub) Run

func (h *Hub) Run()

Run starts the hub

type LatencyHistoryPoint

type LatencyHistoryPoint struct {
	Time    float64 `json:"time"`    // Seconds since test start
	Latency float64 `json:"latency"` // Latency in ms
}

LatencyHistoryPoint represents a latency sample at a point in time

type LatencyPayload

type LatencyPayload struct {
	P50 string `json:"p50"`
	P90 string `json:"p90"`
	P95 string `json:"p95"`
	P99 string `json:"p99"`
}

LatencyPayload represents latency percentiles

type MetricsPayload

type MetricsPayload struct {
	TotalRequests      uint64                 `json:"total_requests"`
	Successes          uint64                 `json:"successes"`
	Failures           uint64                 `json:"failures"`
	CurrentRPS         float64                `json:"current_rps"`
	TargetRPS          int                    `json:"target_rps"`
	AverageLatency     string                 `json:"average_latency"`
	MinLatency         string                 `json:"min_latency"`
	MaxLatency         string                 `json:"max_latency"`
	LatencyPercentiles *LatencyPayload        `json:"latency_percentiles,omitempty"`
	StatusCodes        map[int]uint64         `json:"status_codes"`
	ErrorBreakdown     *ErrorBreakdownPayload `json:"error_breakdown,omitempty"`
	BytesSent          uint64                 `json:"bytes_sent"`
	BytesReceived      uint64                 `json:"bytes_received"`
	ElapsedTime        string                 `json:"elapsed_time"`
	Duration           string                 `json:"duration"`
	Progress           float64                `json:"progress"` // 0-100, -1 for infinite
	LatencyHistory     []LatencyHistoryPoint  `json:"latency_history,omitempty"`
}

MetricsPayload represents real-time metrics

type ResultsResponse

type ResultsResponse struct {
	ID                 string                 `json:"id"`
	Status             string                 `json:"status"`
	Config             *ConfigPayload         `json:"config"`
	Summary            *SummaryPayload        `json:"summary"`
	LatencyPercentiles *LatencyPayload        `json:"latency_percentiles"`
	StatusCodes        map[int]uint64         `json:"status_codes"`
	ErrorBreakdown     *ErrorBreakdownPayload `json:"error_breakdown,omitempty"`
	Timestamp          string                 `json:"timestamp"`
}

ResultsResponse represents the final results

type SPAHandler

type SPAHandler struct {
	// contains filtered or unexported fields
}

SPAHandler serves static files with SPA fallback. For any request that doesn't match a static file, it serves index.html to support client-side routing.

func NewSPAHandler

func NewSPAHandler(staticFS fs.FS) *SPAHandler

NewSPAHandler creates a new SPA handler with the given filesystem.

func (*SPAHandler) ServeHTTP

func (h *SPAHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type SessionManager

type SessionManager struct {
	// contains filtered or unexported fields
}

SessionManager manages the current test session (single session at a time)

func NewSessionManager

func NewSessionManager() *SessionManager

NewSessionManager creates a new session manager

func (*SessionManager) CreateSession

func (sm *SessionManager) CreateSession(id string, cfg *attack.AttackConfig) *TestSession

CreateSession creates a new test session, stopping any existing one

func (*SessionManager) GetCurrent

func (sm *SessionManager) GetCurrent() *TestSession

GetCurrent returns the current session (may be nil)

type SessionStatus

type SessionStatus string

SessionStatus represents the current state of a test session

const (
	StatusIdle      SessionStatus = "idle"
	StatusRunning   SessionStatus = "running"
	StatusCompleted SessionStatus = "completed"
	StatusStopped   SessionStatus = "stopped"
	StatusError     SessionStatus = "error"
)

type StartRequest

type StartRequest struct {
	URL         string   `json:"url"`
	Method      string   `json:"method"`
	Body        string   `json:"body"`
	Headers     []string `json:"headers"`
	Rate        string   `json:"rate"`
	Duration    string   `json:"duration"`
	Timeout     string   `json:"timeout"`
	Workers     uint     `json:"workers"`
	Connections uint     `json:"connections"`
}

StartRequest represents the request body for starting an attack

type StartResponse

type StartResponse struct {
	ID        string `json:"id"`
	Status    string `json:"status"`
	StartedAt string `json:"started_at"`
}

StartResponse represents the response for starting an attack

type StatusResponse

type StatusResponse struct {
	ID          string          `json:"id"`
	Status      string          `json:"status"`
	StartedAt   string          `json:"started_at,omitempty"`
	ElapsedTime string          `json:"elapsed_time,omitempty"`
	Metrics     *MetricsPayload `json:"metrics,omitempty"`
}

StatusResponse represents the response for getting status

type StopResponse

type StopResponse struct {
	ID        string `json:"id"`
	Status    string `json:"status"`
	StoppedAt string `json:"stopped_at"`
}

StopResponse represents the response for stopping an attack

type SummaryPayload

type SummaryPayload struct {
	TotalRequests      uint64  `json:"total_requests"`
	SuccessfulRequests uint64  `json:"successful_requests"`
	FailedRequests     uint64  `json:"failed_requests"`
	TotalElapsedTime   string  `json:"total_elapsed_time"`
	AverageLatency     string  `json:"average_latency"`
	MinLatency         string  `json:"min_latency"`
	MaxLatency         string  `json:"max_latency"`
	ThroughputRPS      float64 `json:"throughput_rps"`
	TargetRPS          int     `json:"target_rps"`
	BytesSent          uint64  `json:"bytes_sent"`
	BytesReceived      uint64  `json:"bytes_received"`
}

SummaryPayload represents the test summary

type TestSession

type TestSession struct {
	ID          string
	Status      SessionStatus
	Config      *attack.AttackConfig
	Metrics     *attack.GlobalMetrics
	StartTime   time.Time
	EndTime     time.Time
	ElapsedTime time.Duration
	StopCh      chan struct{}
	Error       error
	// contains filtered or unexported fields
}

TestSession represents a single load test session

func (*TestSession) Complete

func (s *TestSession) Complete(metrics *attack.GlobalMetrics, elapsed time.Duration)

Complete marks the session as completed with results

func (*TestSession) GetMetrics

func (s *TestSession) GetMetrics() *attack.GlobalMetrics

GetMetrics returns the current metrics

func (*TestSession) GetStatus

func (s *TestSession) GetStatus() SessionStatus

GetStatus returns the current session status

func (*TestSession) IsRunning

func (s *TestSession) IsRunning() bool

IsRunning returns true if the session is currently running

func (*TestSession) SetError

func (s *TestSession) SetError(err error)

SetError marks the session as failed with an error

func (*TestSession) SetMetrics

func (s *TestSession) SetMetrics(metrics *attack.GlobalMetrics)

SetMetrics updates the session metrics (used during streaming)

func (*TestSession) Start

func (s *TestSession) Start()

Start marks the session as running

func (*TestSession) Stop

func (s *TestSession) Stop()

Stop signals the session to stop

type WSMessage

type WSMessage struct {
	Type      string      `json:"type"`
	Timestamp string      `json:"timestamp"`
	Data      interface{} `json:"data,omitempty"`
}

WSMessage represents a WebSocket message

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL