Configuration

Complete reference for the Linux amd64 Config struct, covering networking, TLS, epoll worker sizing, limits, compression, and debugging.

Quick Reference

Minimal config to get started on Linux amd64:

Zero values are not always the runtime values you will see in logs. For example, WorkerCount and Listeners both default to 0 in config and are derived later by the Linux epoll runtime.

go
s := core.New(core.Config{Addr: ":8080", PlainHTTP: true})

s := core.New(core.Config{
    Addr:        ":443",
    TLSCertFile: "cert.pem",
    TLSKeyFile:  "key.pem",
})

s := core.New(core.Config{
    Addr:     ":443",
    HTTPAddr: ":80",
    ACME: &core.ACMEConfig{
        Email:   "you@example.com",
        Domains: []string{"example.com"},
    },
})

Network

FieldTypeDefaultDescription
Addrstring":8443"Listen address (e.g. :443, 0.0.0.0:8080)
HTTPAddrstring"" (auto :80 when Addr is :443)HTTP listen address for ACME challenges & HTTPS redirect
ServerNamestring"ALOS"Value for the Server response header
ProxyModeboolfalseEnable when running behind a reverse proxy / load balancer. The server trusts X-Forwarded-For / X-Real-IP from all peers and rewrites the client IP for every request (rate limiting, logging, and handlers all see the real client). Leave it off when internet-facing, or clients can spoof their IP. Overrides TrustedProxies while on.
TrustedProxies[]stringnilIP ranges/addresses whose X-Forwarded-For / X-Real-IP headers are trusted, e.g. "10.0.0.0/8". Use this instead of ProxyMode when only specific upstream proxies should be trusted. Ignored when ProxyMode is on.

TLS & Certificates

FieldTypeDefaultDescription
TLSCertFilestring""Path to PEM certificate file
TLSKeyFilestring""Path to PEM private key file
Certs[]CertConfignilMulti-domain certs (Domain, CertFile, KeyFile per entry)
DefaultDomainstring""Fallback cert domain for unknown SNI
ACME*ACMEConfignilACME / Let's Encrypt auto-certificate config

CertConfig

FieldTypeDescription
DomainstringSNI hostname to match
CertFilestringPath to PEM certificate
KeyFilestringPath to PEM private key

ACMEConfig

FieldTypeDefaultDescription
Emailstring""ACME account email
Domains[]stringnilDomains to obtain certificates for
CacheDirstring"/etc/letsencrypt"Directory to cache certificates
ACMENodestring""Proxy ACME challenges to this address (e.g. "10.0.0.5:80")

Timeouts

FieldTypeDefaultDescription
ReadTimeouttime.Duration0 (none)Max time to read entire request (0 = no timeout)
WriteTimeouttime.Duration0 (none)Max time to write entire response (0 = no timeout)
IdleTimeouttime.Duration120sKeep-alive idle connection timeout
HandshakeTimeouttime.Duration30sMax time for TLS handshake
ShutdownTimeouttime.Duration30sGraceful shutdown deadline

Size Limits

FieldTypeDefaultDescription
MaxBodySizeint640 (unlimited)Maximum request body size (0 = unlimited)
MaxReadSizeint640Max read size per request (0 = unlimited)
MaxWriteSizeint640Max write size per response (0 = unlimited)
MaxHeaderSizeint8 KBMaximum total header size

Bandwidth

Bandwidth limits use the BandwidthConfig struct with separate upload/download rates and burst size:

FieldTypeDefaultDescription
ConnBandwidthBandwidthConfig{}Per-connection bandwidth limits
GlobalBandwidthBandwidthConfig{}Server-wide bandwidth limits

BandwidthConfig

FieldTypeDescription
MaxUploadRateint64Max upload speed in Mbps (0 = unlimited)
MaxDownloadRateint64Max download speed in Mbps (0 = unlimited)
BurstSizeint64Burst allowance in Mbps before throttling
go
s := core.New(core.Config{
    Addr: ":443",
    ConnBandwidth: core.BandwidthConfig{
        MaxDownloadRate: 40,
        BurstSize:       16,
    },
    GlobalBandwidth: core.BandwidthConfig{
        MaxDownloadRate: 4000,
        BurstSize:       800,
    },
})

Compression

FieldTypeDefaultDescription
EnableCompressboolfalseEnable gzip/deflate response compression
CompressLevelint6Compression level (1 to 9, higher = smaller)
CompressMinSizeint256Minimum response body size to compress

You can also enable compression via the Compress() middleware instead of config, which gives more control over the minimum size threshold.

Connection Limits

FieldTypeDefaultDescription
MaxRequestsPerIPint640 (unlimited)Max concurrent requests from a single IP
MaxConnsPerIPint6420Max concurrent connections per client IP. Under ProxyMode / TrustedProxies the key is the real client IP from X-Forwarded-For / X-Real-IP after the proxy rewrite; otherwise the socket peer IP at accept. 0 applies the default of 20; a negative value disables it. Over-limit connections get 429 and are closed.
MaxConcurrentReqsint640 (unlimited)Max concurrent requests server-wide
go
s := core.New(core.Config{
    Addr:             ":443",
    MaxRequestsPerIP: 100,
    MaxConnsPerIP:    20,
    MaxConcurrentReqs: 10000,
})

Workers & Listeners

FieldTypeDefaultDescription
WorkerCountintauto (hardware threads, capped 128)Linux amd64 epoll TLS worker count. When left 0 it auto-sizes to GOMAXPROCS (hardware threads), clamped to 128. Set it explicitly to override; an explicit value is honored uncapped (e.g. 300 on a 300-thread box).
Listenersintauto (hardware threads, capped 128)Number of SO_REUSEPORT listeners, shared across the :80 redirect, 443 TCP, and 443 UDP (QUIC) sockets. When left 0 it auto-sizes to hardware threads (capped 128) on Linux amd64, so every protocol scales to the box. A UDP/HTTP3 flood or a plain :80 flood can each use all cores, while idle pools park at ~0% CPU. 1 on other platforms. Set explicitly to override.

Miscellaneous

FieldTypeDefaultDescription
PlainHTTPboolfalseRun without TLS (plain HTTP mode)
DisableHTTP2boolfalseWhen true the server never negotiates HTTP/2 and only serves HTTP/1.1
DebugboolfalseEnable debug logging (connections, TLS, errors)
LogRequestsbooltrueLog every request (method, path, status, duration)

Server Hooks

Hooks let you intercept the request lifecycle without writing middleware. They run in registration order, and you can register multiple hooks of each type.

MethodSignatureDescription
OnRequestfunc(*Request, *Response) boolCalled before route handlers. Return false to reject the request; the handler will not run.
OnResponsefunc(*Request, *Response)Called after every response, before compression. Use for logging, metrics, or header injection.
go
s.OnRequest(func(req *core.Request, resp *core.Response) bool {
    if req.Header("X-Block") == "true" {
        resp.Status(403).String("Blocked")
        return false
    }
    return true
})

s.OnResponse(func(req *core.Request, resp *core.Response) {
    log.Printf("%s %s -> %d", req.Method, req.Path, resp.StatusCode)
})

Static File Serving

Serve files from a directory with automatic MIME type detection, path traversal protection, and optional directory listing.

FunctionSignatureDescription
StaticStatic(urlPrefix string, cfg StaticConfig) HandlerFuncServe a directory with full configuration
StaticDirStaticDir(urlPrefix, root string) HandlerFuncConvenience shorthand with default settings

StaticConfig

FieldTypeDefaultDescription
Rootstring""Root directory to serve files from
Indexstring"index.html"Default file to serve for directory requests
BrowseboolfalseEnable directory listing when no index file exists

Path traversal protection is built in: requests containing .., null bytes, or backslashes are rejected, and the resolved path is validated to stay within the root directory. MIME types are detected from file extensions (~40 types supported).

go
s.Router.GET("/static/*filepath", core.Static("/static", core.StaticConfig{
    Root:   "./public",
    Index:  "index.html",
    Browse: false,
}))

s.Router.GET("/files/*filepath", core.StaticDir("/files", "./uploads"))

Graceful Shutdown

Use s.Shutdown to gracefully drain active connections before stopping the server. Pass a context with a deadline to bound the drain time. Shutdown stops ACME renewal, rate-limit cleanup, and closes all listeners.

MethodSignatureDescription
ShutdownShutdown(ctx context.Context) errorGracefully drains connections within the context deadline
go
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := s.Shutdown(ctx); err != nil {
    log.Printf("shutdown: %v", err)
}

Full Example

A production-ready configuration using most available options:

go
s := core.New(core.Config{
    Addr:       ":443",
    HTTPAddr:   ":80",
    ServerName: "my-app",

    ACME: &core.ACMEConfig{
        Email:    "admin@example.com",
        Domains:  []string{"example.com", "api.example.com"},
        CacheDir: "/etc/alos/certs",
    },

    ReadTimeout:         15 * time.Second,
    WriteTimeout:        30 * time.Second,
    IdleTimeout:         120 * time.Second,
    HandshakeTimeout:    5 * time.Second,
    ShutdownTimeout:     30 * time.Second,

    MaxBodySize:   10 * 1024 * 1024,
    MaxHeaderSize: 16 * 1024,

    MaxRequestsPerIP:  100,
    MaxConcurrentReqs: 10000,

    ConnBandwidth: core.BandwidthConfig{
        MaxDownloadRate: 40,
        BurstSize:       16,
    },
    GlobalBandwidth: core.BandwidthConfig{
        MaxDownloadRate: 4000,
        BurstSize:       800,
    },

    EnableCompress: true,
    CompressLevel:   6,
    CompressMinSize: 1024,

    WorkerCount: 8,

    TrustedProxies: []string{"10.0.0.0/8", "172.16.0.0/12"},

    Debug:       false,
    LogRequests: true,
})