api

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 14 Imported by: 0

README ΒΆ

🌐 REST API Server & Router (internal/api)

internal/api provides HTTP RESTful API routing, JSON response formatting, CORS middleware, JWT authentication middleware, and tenant endpoints for PingGopher.


πŸ“‘ API Endpoints Reference

1. System Health
  • GET /health (Public): Returns API status.
2. Tenant Authentication
  • POST /v1/auth/signup (Public): Registers a new tenant user. Expects {"email": "...", "password": "..."}. Returns JWT token.
  • POST /v1/auth/login (Public): Authenticates user credentials. Returns JWT token.
3. Monitor Management (JWT Authenticated)

Requires Authorization: Bearer <TOKEN> header.

  • POST /v1/monitors: Creates a new target monitor.
  • GET /v1/monitors: Lists user's monitors.
  • GET /v1/monitors/{id}: Gets monitor details.
  • PUT /v1/monitors/{id}: Updates monitor target URL, check interval, or status (UP / PAUSED).
  • DELETE /v1/monitors/{id}: Deletes monitor target.
4. Telemetry Logs & Incidents (JWT Authenticated)
  • GET /v1/monitors/{id}/logs: Returns recent probe execution logs (PingLog). Optional query param: ?limit=50.
  • GET /v1/monitors/{id}/incidents: Returns outage incident history.

πŸ”’ Security & Middleware

  • CORSMiddleware: Injects headers for cross-origin browser dashboards.
  • AuthMiddleware: Validates JWT Bearer tokens and attaches tenant UserID to request contexts.

πŸ§ͺ Testing & Verification

Automated Integration Test Suite (api_test.go)
Test Method Test Focus & Verification
TestSignupAndLoginAPI Tests user signup (POST /v1/auth/signup), duplicate email rejection (409 Conflict), and login authentication (POST /v1/auth/login).
TestMonitorCRUDAPI Tests authenticated monitor creation (POST /v1/monitors), listing (GET /v1/monitors), updating (PUT), and deletion (DELETE) using JWT Bearer headers.
TestTelemetryAndIncidentsAPI Tests querying execution PingLog entries (GET /v1/monitors/{id}/logs) and outage Incident records.
Running API Integration Tests
go test -v ./internal/api

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (
	UserIDContextKey    contextKey = "user_id"
	UserEmailContextKey contextKey = "user_email"
)

Variables ΒΆ

This section is empty.

Functions ΒΆ

func AuthMiddleware ΒΆ

func AuthMiddleware(jwtSecret string, next http.HandlerFunc) http.HandlerFunc

AuthMiddleware validates JWT Bearer tokens and attaches UserID to request context.

func CORSMiddleware ΒΆ

func CORSMiddleware(next http.Handler) http.Handler

CORSMiddleware enables Cross-Origin Resource Sharing headers for Web Dashboard requests.

func GetUserIDFromContext ΒΆ

func GetUserIDFromContext(r *http.Request) (uuid.UUID, error)

GetUserIDFromContext retrieves the authenticated UserID from request context.

func JSONError ΒΆ

func JSONError(w http.ResponseWriter, statusCode int, message string)

JSONError sends a JSON response formatted error message.

func JSONResponse ΒΆ

func JSONResponse(w http.ResponseWriter, statusCode int, data interface{})

JSONResponse sends a JSON response with status code and data payload.

Types ΒΆ

type APIHandler ΒΆ

type APIHandler struct {
	DB     *gorm.DB
	Config *config.Config
}

func NewAPIHandler ΒΆ

func NewAPIHandler(database *gorm.DB, cfg *config.Config) *APIHandler

func (*APIHandler) CreateMonitorHandler ΒΆ

func (h *APIHandler) CreateMonitorHandler(w http.ResponseWriter, r *http.Request)

CreateMonitorHandler creates a new monitor target for the authenticated tenant.

func (*APIHandler) DeleteMonitorHandler ΒΆ

func (h *APIHandler) DeleteMonitorHandler(w http.ResponseWriter, r *http.Request)

DeleteMonitorHandler removes a monitor target.

func (*APIHandler) GetMonitorHandler ΒΆ

func (h *APIHandler) GetMonitorHandler(w http.ResponseWriter, r *http.Request)

GetMonitorHandler fetches details for a specific monitor.

func (*APIHandler) GetMonitorIncidentsHandler ΒΆ

func (h *APIHandler) GetMonitorIncidentsHandler(w http.ResponseWriter, r *http.Request)

GetMonitorIncidentsHandler returns outage incident history for a monitor.

func (*APIHandler) GetMonitorLogsHandler ΒΆ

func (h *APIHandler) GetMonitorLogsHandler(w http.ResponseWriter, r *http.Request)

GetMonitorLogsHandler returns recent PingLog execution telemetry for a monitor.

func (*APIHandler) ListMonitorsHandler ΒΆ

func (h *APIHandler) ListMonitorsHandler(w http.ResponseWriter, r *http.Request)

ListMonitorsHandler lists all monitors owned by the authenticated tenant.

func (*APIHandler) LoginHandler ΒΆ

func (h *APIHandler) LoginHandler(w http.ResponseWriter, r *http.Request)

LoginHandler authenticates user credentials and returns a JWT token.

func (*APIHandler) PublicStatusHandler ΒΆ

func (h *APIHandler) PublicStatusHandler(w http.ResponseWriter, r *http.Request)

PublicStatusHandler returns an unauthenticated system operational summary for public status pages.

func (*APIHandler) SetupRouter ΒΆ

func (h *APIHandler) SetupRouter() http.Handler

SetupRouter initializes the HTTP router and registers all public and authenticated REST endpoints.

func (*APIHandler) SignupHandler ΒΆ

func (h *APIHandler) SignupHandler(w http.ResponseWriter, r *http.Request)

SignupHandler handles new tenant user registration.

func (*APIHandler) UpdateMonitorHandler ΒΆ

func (h *APIHandler) UpdateMonitorHandler(w http.ResponseWriter, r *http.Request)

UpdateMonitorHandler updates monitor parameters or status.

type AuthRequest ΒΆ

type AuthRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

type AuthResponse ΒΆ

type AuthResponse struct {
	Token string  `json:"token"`
	User  db.User `json:"user"`
}

type CreateMonitorRequest ΒΆ

type CreateMonitorRequest struct {
	Name                 string `json:"name"`
	URL                  string `json:"url"`
	CheckIntervalSeconds int    `json:"check_interval_seconds"`
	WebhookURL           string `json:"webhook_url,omitempty"`
}

type PublicIncidentReport ΒΆ

type PublicIncidentReport struct {
	ID          string            `json:"id"`
	MonitorName string            `json:"monitor_name"`
	StartedAt   time.Time         `json:"started_at"`
	Cause       string            `json:"cause"`
	Status      db.IncidentStatus `json:"status"`
}

type PublicMonitorCard ΒΆ

type PublicMonitorCard struct {
	ID                   string           `json:"id"`
	Name                 string           `json:"name"`
	CheckIntervalSeconds int              `json:"check_interval_seconds"`
	Status               db.MonitorStatus `json:"status"`
	SSLExpirationDate    *time.Time       `json:"ssl_expiration_date,omitempty"`
}

type PublicStatusResponse ΒΆ

type PublicStatusResponse struct {
	SystemStatus    string                 `json:"system_status"` // "All Systems Operational" or "Partial System Outage"
	TotalMonitors   int                    `json:"total_monitors"`
	UpMonitors      int                    `json:"up_monitors"`
	DownMonitors    int                    `json:"down_monitors"`
	Monitors        []PublicMonitorCard    `json:"monitors"`
	ActiveIncidents []PublicIncidentReport `json:"active_incidents"`
}

type ResponseEnvelope ΒΆ

type ResponseEnvelope struct {
	Success bool        `json:"success"`
	Data    interface{} `json:"data,omitempty"`
	Error   string      `json:"error,omitempty"`
}

Response Envelope for standardized REST API JSON responses.

type UpdateMonitorRequest ΒΆ

type UpdateMonitorRequest struct {
	Name                 string           `json:"name,omitempty"`
	URL                  string           `json:"url,omitempty"`
	CheckIntervalSeconds int              `json:"check_interval_seconds,omitempty"`
	Status               db.MonitorStatus `json:"status,omitempty"`
	WebhookURL           string           `json:"webhook_url,omitempty"`
}

Jump to

Keyboard shortcuts

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