Skip to content

HTTPS Go server / API gateway for Vibe Coding

License

Notifications You must be signed in to change notification settings

maxbolgarin/servex

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

103 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Servex - Production-Ready HTTP Server for Go

Go Version GoDoc Build Coverage GoReport MIT

Servex eliminates HTTP server boilerplate in Go. Focus on business logic while getting production-ready features out of the box.

Features

  • 🚀 Zero Boilerplate - Configure once, code business logic
  • đź”’ Security First - JWT auth, rate limiting, request filtering, security headers, audit logging
  • 🔄 Reverse Proxy / API Gateway - Load balancing, health checks, traffic analysis
  • ⚡ Native Compatibility - Works seamlessly with existing net/http code

Quick Start

go get -u github.com/maxbolgarin/servex/v2

Basic Server

server, _ := servex.New(servex.ProductionPreset()...)
server.HandleFunc("/hello", helloHandler)
server.StartWithWaitSignals(context.Background(), ":8080", "")

Context Helper

func handler(w http.ResponseWriter, r *http.Request) {
    ctx := servex.C(w, r)

    request, err := servex.ReadJSON[Request](r)
    if err != nil {
        ctx.BadRequest(err, "invalid request")
        return
    }

    ctx.Response(http.StatusOK, response)
}

Presets

Quick configurations for common scenarios:

Preset Use Case
DevelopmentPreset() Development with minimal setup
ProductionPreset() Production with security, rate limiting, monitoring
APIServerPreset() REST APIs
WebAppPreset() Web applications with security headers
MicroservicePreset() Fast timeouts, minimal security
HighSecurityPreset() Maximum security features
QuickTLSPreset(cert, key) Production + SSL

Features & Configuration

Feature Configuration Options
Authentication WithAuth(config) - Full JWT auth with database
WithAuthToken(token) - Simple bearer token
WithAuthMemoryDatabase() - In-memory user storage
WithAuthKey(accessKey, refreshKey) - Custom JWT keys
WithAuthTokensDuration(access, refresh) - Token lifetimes
WithAuthIssuer(issuer) - JWT issuer
WithAuthBasePath(path) - Auth routes prefix
WithAuthInitialRoles(roles...) - Default user roles
Rate Limiting WithRPM(requests) - Requests per minute
WithRPS(requests) - Requests per second
WithRequestsPerInterval(requests, interval) - Custom interval
WithBurstSize(size) - Burst allowance
WithRateLimitConfig(config) - Full configuration
WithRateLimitExcludePaths(paths...) - Exclude paths
WithRateLimitIncludePaths(paths...) - Include only paths
Request Filtering WithBlockedIPs(ips...) - Block IP ranges
WithAllowedIPs(ips...) - Allow only IPs
WithBlockedUserAgents(agents...) - Block user agents
WithBlockedUserAgentsRegex(patterns...) - Block by regex
WithAllowedHeaders(headers) - Allow headers
WithBlockedHeaders(headers) - Block headers
WithAllowedQueryParams(params) - Allow query params
WithBlockedQueryParams(params) - Block query params
WithFilterConfig(config) - Full configuration
Security Headers WithSecurityHeaders() - Basic headers
WithStrictSecurityHeaders() - Strict CSP, HSTS
WithContentSecurityPolicy(policy) - Custom CSP
WithHSTSHeader(maxAge, includeSubdomains, preload) - HSTS config
WithSecurityConfig(config) - Full configuration
CSRF Protection WithCSRFProtection() - Enable CSRF
WithCSRFTokenName(name) - Token header name
WithCSRFCookieName(name) - Cookie name
WithCSRFCookieHttpOnly(httpOnly) - HttpOnly flag
WithCSRFCookieSecure(secure) - Secure flag
WithCSRFTokenEndpoint(endpoint) - Token endpoint
CORS WithCORS() - Enable with defaults
WithCORSAllowOrigins(origins...) - Allowed origins
WithCORSAllowMethods(methods...) - Allowed methods
WithCORSAllowHeaders(headers...) - Allowed headers
WithCORSAllowCredentials() - Allow credentials
WithCORSMaxAge(seconds) - Preflight cache
WithCORSConfig(config) - Full configuration
Compression WithCompression() - Enable gzip
WithCompressionLevel(level) - Level 1-9
WithCompressionMinSize(size) - Min size to compress
WithCompressionTypes(types...) - Content types
WithCompressionConfig(config) - Full configuration
Caching WithCachePublic(maxAge) - Public cache
WithCachePrivate(maxAge) - Private cache
WithCacheStaticAssets(maxAge) - Static file cache
WithCacheNoCache() - Disable caching
WithCacheControl(control) - Custom Cache-Control
WithCacheConfig(config) - Full configuration
Static Files / SPA WithStaticFiles(dir, prefix) - Serve static files
WithSPAMode(dir, indexFile) - SPA mode
WithStaticFileConfig(config) - Full configuration
WithStaticFileCache(maxAge, rules...) - Cache rules
Reverse Proxy WithProxyConfig(config) - Full proxy configuration
Supports load balancing, health checks, path rewriting
HTTPS / TLS WithCertificate(cert) - TLS certificate
WithCertificateFromFile(cert, key) - Load from files
WithHTTPSRedirect() - Redirect HTTP to HTTPS
WithHTTPSRedirectTemporary() - 307 redirect
WithHTTPSRedirectConfig(config) - Full redirect config
Logging & Monitoring WithLogger(logger) - Custom logger
WithDefaultAuditLogger() - Security audit logs
WithAuditLogger(logger) - Custom audit logger
WithDisableRequestLogging() - Disable request logs
WithNoLogClientErrors() - Skip 4xx errors
WithLogFields(fields...) - Additional log fields
Health & Metrics WithHealthEndpoint() - Enable /health
WithHealthPath(path) - Custom health path
WithDefaultMetrics(path) - Prometheus metrics
WithMetrics(metrics) - Custom metrics
WithDisableHealthEndpoint() - Disable health
Server Timeouts WithReadTimeout(duration) - Request read timeout
WithReadHeaderTimeout(duration) - Header read timeout
WithIdleTimeout(duration) - Keep-alive timeout
WithMaxHeaderBytes(size) - Max header size
Request Size Limits WithMaxRequestBodySize(size) - Max body size
WithMaxJSONBodySize(size) - Max JSON size
WithMaxFileUploadSize(size) - Max file size
WithMaxMultipartMemory(size) - Multipart memory
WithRequestSizeLimits() - Enable defaults
WithStrictRequestSizeLimits() - Strict limits

Core Features

Authentication

Built-in JWT authentication with user management:

server, _ := servex.New(
    servex.WithAuth(servex.AuthConfig{
        Database:            authDB,
        RolesOnRegister:     []servex.UserRole{"user"},
        AccessTokenDuration: 15 * time.Minute,
    }),
)

// Auto-registers: /auth/login, /auth/register, /auth/refresh, /auth/logout
server.HandleFuncWithAuth("/admin", adminHandler, "admin")

Rate Limiting

Protect all your APIs:

server, _ := servex.New(servex.WithRPM(100)) // 100 requests per minute

Or per-endpoint limits via register after server creation:

locationConfigs := []servex.LocationRateLimitConfig{
    {
        PathPatterns: []string{"/auth/login"},
        Config: servex.RateLimitConfig{
            RequestsPerInterval: 5,
            Interval: time.Minute,
        },
    },
}
servex.RegisterLocationBasedRateLimitMiddleware(server.Router(), locationConfigs)

Request Filtering

Block malicious traffic:

server, _ := servex.New(
    servex.WithBlockedIPs("192.0.2.0/24"),
    servex.WithBlockedUserAgentsRegex(`(?i).*(bot|crawler).*`),
)

Reverse Proxy

L7 reverse proxy with load balancing:

proxyConfig := servex.ProxyConfiguration{
    Enabled: true,
    Rules: []servex.ProxyRule{
        {
            PathPrefix: "/api/",
            Backends: []servex.Backend{
                {URL: "http://backend1:8080", Weight: 2},
                {URL: "http://backend2:8080", Weight: 1},
            },
            LoadBalancing: servex.WeightedRoundRobinStrategy,
            StripPrefix:   "/api",
        },
    },
}

server, _ := servex.New(servex.WithProxyConfig(proxyConfig))

Security Headers

server, _ := servex.New(
    servex.WithStrictSecurityHeaders(), // CSP, HSTS, etc.
    servex.WithCSRFProtection(),
)

Audit Logging

Track security events:

server, _ := servex.New(
    servex.WithDefaultAuditLogger(),
    servex.WithAuth(authConfig),
)
// Logs: auth events, rate limits, filter blocks, CSRF violations

Context Helpers

ctx := servex.C(w, r)

// Request
requestID := ctx.RequestID()
apiVersion := ctx.APIVersion()      // Extracts 'v1' from /api/v1/...
userID := ctx.Path("id")            // Path parameter
sort := ctx.Query("sort")           // Query parameter
user, _ := servex.ReadJSON[User](r)

// Response
ctx.Response(http.StatusOK, data)
ctx.BadRequest(err, "invalid input")
ctx.NotFound(err, "not found")
ctx.InternalServerError(err, "error")

// Cookies
cookie, _ := ctx.Cookie("session")
ctx.SetCookie("session", "token", 3600, true, true)

Configuration Options

Servex provides 100+ options via With... pattern:

server, _ := servex.New(
    // Server
    servex.WithReadTimeout(30*time.Second),
    servex.WithLogger(slog.Default()),

    // Security
    servex.WithStrictSecurityHeaders(),
    servex.WithRPM(1000),
    servex.WithBlockedIPs("10.0.0.0/8"),

    // Features
    servex.WithHealthEndpoint(),
    servex.WithDefaultMetrics(),
    servex.WithCompression(),
    servex.WithCORS(),

    // Static Files / SPA
    servex.WithSPAMode("build", "index.html"),
)

See Complete Configuration Reference for all options.

HTTP Method Shortcuts

server.GET("/users", listUsers)
server.POST("/users", createUser)
server.PUT("/users/{id}", updateUser)
server.DELETE("/users/{id}", deleteUser)

// With authentication
server.GetWithAuth("/admin", adminHandler, "admin")
server.PostWithAuth("/api/data", dataHandler, "user")

Server Start Options

// 1. Basic start (non-blocking)
server.Start(":8080", ":8443")

// 2. With automatic shutdown on context cancel
server.StartWithShutdown(ctx, ":8080", "")

// 3. Wait for signals (Ctrl+C) - blocking
server.StartWithWaitSignals(ctx, ":8080", "")

// 4. Separate HTTP/HTTPS
server.StartHTTP(":8080")
server.StartHTTPS(":8443")

Complete Configuration Reference

View all configuration options (100+)

TLS & Certificates

  • WithCertificate(cert) - Set TLS certificate
  • WithCertificateFromFile(cert, key) - Load from files

Timeouts

  • WithReadTimeout(duration) - Request read timeout
  • WithIdleTimeout(duration) - Keep-alive timeout

Authentication

  • WithAuth(config) - JWT authentication
  • WithAuthMemoryDatabase() - In-memory user database
  • WithAuthToken(token) - Simple bearer token
  • WithAuthTokensDuration(access, refresh) - Token lifetimes

Rate Limiting

  • WithRPM(requests) - Requests per minute
  • WithRPS(requests) - Requests per second
  • WithBurstSize(size) - Burst allowance
  • WithRateLimitKeyFunc(func) - Custom rate limit key

Request Filtering

  • WithBlockedIPs(ips...) - Block IP ranges
  • WithAllowedIPs(ips...) - Allow only specific IPs
  • WithBlockedUserAgents(agents...) - Block user agents
  • WithBlockedUserAgentsRegex(patterns...) - Block by regex

Security

  • WithSecurityHeaders() - Basic security headers
  • WithStrictSecurityHeaders() - Strict CSP, HSTS
  • WithCSRFProtection() - CSRF token validation
  • WithContentSecurityPolicy(policy) - Custom CSP

CORS

  • WithCORS() - Enable with defaults
  • WithCORSAllowOrigins(origins...) - Allowed origins
  • WithCORSAllowMethods(methods...) - Allowed methods
  • WithCORSAllowCredentials() - Allow credentials

Caching

  • WithCachePublic(maxAge) - Public cache
  • WithCachePrivate(maxAge) - Private cache
  • WithCacheStaticAssets(maxAge) - Cache static files
  • WithCacheNoCache() - Disable caching

Logging & Monitoring

  • WithLogger(logger) - Custom logger
  • WithDefaultAuditLogger() - Security audit logging
  • WithHealthEndpoint() - Health check endpoint
  • WithDefaultMetrics() - Prometheus metrics

Performance

  • WithCompression() - Gzip compression
  • WithCompressionLevel(level) - Compression level (1-9)
  • WithMaxRequestBodySize(size) - Limit request size

Static Files

  • WithStaticFiles(dir, prefix) - Serve static files
  • WithSPAMode(dir, index) - Single Page Application mode

Reverse Proxy

  • WithProxyConfig(config) - Complete proxy configuration

Why Servex?

Before Servex

func handler(w http.ResponseWriter, r *http.Request) {
    bodyBytes, _ := io.ReadAll(r.Body)
    var request Request
    json.Unmarshal(bodyBytes, &request)

    respBytes, _ := json.Marshal(resp)
    w.Header().Set("Content-Type", "application/json")
    w.Write(respBytes)
}

With Servex

func handler(w http.ResponseWriter, r *http.Request) {
    ctx := servex.C(w, r)
    request, _ := servex.ReadJSON[Request](r)
    ctx.Response(http.StatusOK, resp)
}

Examples

See examples/ for complete working examples:

  • Basic server
  • Authentication
  • Rate limiting
  • Reverse proxy
  • SPA serving

Contributing

Pull requests and issues welcome! See LICENSE for terms.

License

MIT License - see LICENSE file.


About

HTTPS Go server / API gateway for Vibe Coding

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •  

Languages