http

package
v0.0.37 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2025 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package http provides documentation generation utilities for EVE services.

Package http provides common HTTP server utilities for EVE services. This file contains the RunServer helper for standardized service management.

Package http provides common HTTP server utilities for EVE services. This package includes standard middleware, health checks, and server setup patterns used across the EVE ecosystem.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIKeyMiddleware added in v0.0.28

func APIKeyMiddleware(apiKey string) echo.MiddlewareFunc

APIKeyMiddleware creates a middleware that validates API keys

func CustomHTTPErrorHandler added in v0.0.28

func CustomHTTPErrorHandler(err error, c echo.Context)

CustomHTTPErrorHandler provides a standard error handler for Echo

func DocumentationHandler added in v0.0.30

func DocumentationHandler(config ServiceDocConfig) echo.HandlerFunc

DocumentationHandler creates a documentation page for a service

func GetPortInt added in v0.0.29

func GetPortInt(envVar string, defaultPort int) int

GetPortInt parses a port from environment variable with a default fallback

func GracefulShutdown added in v0.0.28

func GracefulShutdown(e *echo.Echo, timeout time.Duration) error

GracefulShutdown performs a graceful shutdown of the Echo server

func HealthCheckHandler added in v0.0.28

func HealthCheckHandler(serviceName, version string) echo.HandlerFunc

HealthCheckHandler returns a standard health check handler

func HealthCheckHandlerWithDetails added in v0.0.28

func HealthCheckHandlerWithDetails(serviceName, version string, detailsFunc func() map[string]interface{}) echo.HandlerFunc

HealthCheckHandlerWithDetails returns a health check handler with custom details

func JSONContentTypeMiddleware added in v0.0.28

func JSONContentTypeMiddleware() echo.MiddlewareFunc

JSONContentTypeMiddleware ensures JSON content type for API responses

func NewEchoServer added in v0.0.28

func NewEchoServer(config ServerConfig) *echo.Echo

NewEchoServer creates a new Echo server with standard middleware

func RunServer added in v0.0.29

func RunServer(config RunServerConfig, setupFunc SetupFunc) error

RunServer creates and runs an Echo server with standard EVE patterns:

  • Creates Echo instance with standard middleware
  • Adds health check endpoint
  • Registers with service registry (if enabled)
  • Sets up signal handling for graceful shutdown
  • Unregisters from service registry on shutdown

Example usage:

cfg := http.DefaultRunServerConfig("myservice", "My Service", "1.0.0")
cfg.Port = 8090
cfg.Capabilities = []string{"storage", "query"}

err := http.RunServer(cfg, func(e *echo.Echo) error {
    e.POST("/api/action", handleAction)
    return nil
})

func SecurityHeadersMiddleware added in v0.0.28

func SecurityHeadersMiddleware() echo.MiddlewareFunc

SecurityHeadersMiddleware adds security headers to responses

func StartServer added in v0.0.28

func StartServer(e *echo.Echo, config ServerConfig) error

StartServer starts an Echo server with graceful shutdown support

Types

type EndpointDoc added in v0.0.30

type EndpointDoc struct {
	Method      string
	Path        string
	Description string
	RequestBody string
	Response    string
}

EndpointDoc describes an API endpoint

type ErrorResponse added in v0.0.28

type ErrorResponse struct {
	Error   string                 `json:"error"`
	Message string                 `json:"message,omitempty"`
	Details map[string]interface{} `json:"details,omitempty"`
}

ErrorResponse represents a standard error response

type HealthResponse added in v0.0.28

type HealthResponse struct {
	Status  string                 `json:"status"`
	Service string                 `json:"service,omitempty"`
	Version string                 `json:"version,omitempty"`
	Details map[string]interface{} `json:"details,omitempty"`
}

HealthResponse represents a health check response

type Request

type Request struct {
	// HTTP basics
	Method string // GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
	URL    string // Target URL

	// Headers and authentication
	Headers map[string]string // HTTP headers

	// Request body options
	JSONBody string            // JSON body for application/json requests
	FormData map[string]string // Form data (key-value pairs)
	Files    map[string]string // Files to upload (form field -> file path)
	RawBody  []byte            // Raw body bytes (for custom content types)

	// Response handling
	SaveTo string // Save response to file (optional)

	// Network configuration
	Timeout        int  // Timeout in seconds (0 = default 30s)
	FollowRedirect bool // Follow HTTP redirects (default: true)
	MaxRedirects   int  // Maximum number of redirects (default: 10)

	// Retry configuration
	RetryCount    int           // Number of retries on failure (default: 0)
	RetryBackoff  string        // "exponential" or "linear" (default: "exponential")
	RetryInterval time.Duration // Initial retry interval (default: 1s)

	// Caching
	UseCache       bool   // Enable HTTP caching (ETag, Last-Modified)
	CacheValidator string // Custom cache validation logic

	// TLS/SSL
	InsecureSkipVerify bool // Skip TLS certificate verification (dangerous!)

	// Advanced
	UserAgent string // Custom User-Agent header
	Proxy     string // HTTP proxy URL
}

Request represents an HTTP operation with all configuration options

func FromSemanticRequest

func FromSemanticRequest(sr *semantic.SemanticRequest) *Request

FromSemanticRequest creates a Request from Schema.org representation

func NewRequest

func NewRequest(method, url string) *Request

NewRequest creates a new Request with sensible defaults

func (*Request) ToJSONLD

func (r *Request) ToJSONLD() (string, error)

ToJSONLD exports the request as JSON-LD for interoperability

func (*Request) ToSemanticRequest

func (r *Request) ToSemanticRequest() *semantic.SemanticRequest

ToSemanticRequest converts a Request to Schema.org DigitalDocument representation

type Response

type Response struct {
	StatusCode int               // HTTP status code
	Status     string            // HTTP status message
	Headers    map[string]string // Response headers
	Body       []byte            // Response body
	BodyString string            // Response body as string
	FromCache  bool              // Whether response came from cache
	Duration   time.Duration     // Request duration
}

Response represents an HTTP response with metadata

func Execute

func Execute(req *Request) (*Response, error)

Execute performs an HTTP request and returns the response

func (*Response) IsClientError

func (r *Response) IsClientError() bool

IsClientError returns true if status code is 4xx

func (*Response) IsRedirect

func (r *Response) IsRedirect() bool

IsRedirect returns true if status code is 3xx

func (*Response) IsServerError

func (r *Response) IsServerError() bool

IsServerError returns true if status code is 5xx

func (*Response) IsSuccess

func (r *Response) IsSuccess() bool

IsSuccess returns true if status code is 2xx

func (*Response) ToJSONLD

func (r *Response) ToJSONLD() (string, error)

ToJSONLD exports the response as JSON-LD

func (*Response) ToSemanticResponse

func (r *Response) ToSemanticResponse() *semantic.SemanticResponse

ToSemanticResponse converts a Response to Schema.org representation

type RunServerConfig added in v0.0.29

type RunServerConfig struct {
	// Service identification
	ServiceID   string
	ServiceName string
	Version     string
	Description string

	// Server configuration
	Port            int
	Debug           bool
	BodyLimit       string
	ReadTimeout     time.Duration
	WriteTimeout    time.Duration
	ShutdownTimeout time.Duration
	AllowedOrigins  []string
	RateLimit       float64

	// Registry configuration (optional)
	EnableRegistry bool
	Directory      string   // Service directory (for registry)
	Binary         string   // Binary name (for registry)
	Capabilities   []string // Service capabilities (for registry)

	// Logger (optional, will create one if nil)
	Logger *common.ContextLogger
}

RunServerConfig contains configuration for running an EVE service

func DefaultRunServerConfig added in v0.0.29

func DefaultRunServerConfig(serviceID, serviceName, version string) RunServerConfig

DefaultRunServerConfig returns a RunServerConfig with sensible defaults

type ServerConfig added in v0.0.28

type ServerConfig struct {
	Port            int
	Debug           bool
	BodyLimit       string // e.g., "100M"
	ReadTimeout     time.Duration
	WriteTimeout    time.Duration
	ShutdownTimeout time.Duration
	AllowedOrigins  []string // For CORS
	RateLimit       float64  // Requests per second (0 = no limit)
}

ServerConfig contains configuration for creating an Echo server

func DefaultServerConfig added in v0.0.28

func DefaultServerConfig() ServerConfig

DefaultServerConfig returns a server config with sensible defaults

type ServiceDocConfig added in v0.0.30

type ServiceDocConfig struct {
	ServiceID    string
	ServiceName  string
	Description  string
	Version      string
	Port         int
	Capabilities []string
	Endpoints    []EndpointDoc
}

ServiceDocConfig contains configuration for service documentation

type SetupFunc added in v0.0.29

type SetupFunc func(*echo.Echo) error

SetupFunc is a function that sets up routes and handlers on an Echo instance

Jump to

Keyboard shortcuts

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