Back to Home

Headless CMS on Go without CGO and frameworks

Minimal headless CMS on Go for landing pages without external dependencies. Uses modernc/sqlite, net/http, channels for Bitrix24. Full security and zero-config launch.

Creating headless CMS on Go: 20 MB without dependencies
Advertisement 728x90

Minimalist Headless CMS in Pure Go: Architecture and Implementation

The key decision is using modernc.org/sqlite instead of mattn/go-sqlite3. This is a pure Go port of SQLite with a compatible database/sql API, requiring no C compiler.

import (
    "database/sql"
    _ "modernc.org/sqlite"
)

func Open(path string) (*sql.DB, error) {
    db, err := sql.Open("sqlite", path)
    if err != nil {
        return nil, err
    }

    // WAL mode for concurrent access
    pragmas := []string{
        "PRAGMA journal_mode=WAL",
        "PRAGMA busy_timeout=5000",
        "PRAGMA foreign_keys=ON",
        "PRAGMA synchronous=NORMAL",
    }
    for _, p := range pragmas {
        if _, err := db.Exec(p); err != nil {
            return nil, fmt.Errorf("pragma %q: %w", p, err)
        }
    }
    return db, nil
}

WAL mode enables parallel reading during writes—critical for simultaneous API and admin panel operation.

Routing and Middleware with net/http

Avoiding Gin/Echo/Chi in favor of http.ServeMux reduces dependencies and simplifies debugging:

Google AdInline article slot
mux := http.NewServeMux()

// Public API
mux.Handle("/api/leads", rateLimiter(http.HandlerFunc(h.CreateLead)))
mux.Handle("/api/news", http.HandlerFunc(h.ListNews))

// Admin panel
mux.Handle("/admin/", authMiddleware(sessionStore, adminHandler))

Middleware chain: logger → rateLimiter → auth → csrfCheck → handler. Each is an independent, test-covered function.

Asynchronous Integration with Bitrix24

Lead submissions to CRM are handled asynchronously via Go channels and a worker pool—no Redis or Celery required:

type Worker struct {
    db      *sql.DB
    queue   chan Job
    webhook string
    wg      sync.WaitGroup
}

func NewWorker(db *sql.DB, webhook string, poolSize int) *Worker {
    w := &Worker{
        db:      db,
        queue:   make(chan Job, 100),
        webhook: webhook,
    }
    for i := 0; i < poolSize; i++ {
        w.wg.Add(1)
        go w.process()
    }
    return w
}

func (w *Worker) Enqueue(job Job) {
    select {
    case w.queue <- job:
    default:
        log.Printf("bitrix queue full, lead %d will be retried manually", job.LeadID)
    }
}

A buffer of 100 jobs, graceful shutdown with 30-second timeout.

Google AdInline article slot

CSRF Protection with HMAC-SHA256

Admin forms using HTMX are protected with synchronized tokens:

func generateCSRFToken(sessionID, secret string) string {
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write([]byte(sessionID))
    return hex.EncodeToString(mac.Sum(nil))
}

func validateCSRFToken(r *http.Request, sessionID, secret string) bool {
    token := r.FormValue("csrf_token")
    if token == "" {
        token = r.Header.Get("X-CSRF-Token")
    }
    expected := generateCSRFToken(sessionID, secret)
    return hmac.Equal([]byte(token), []byte(expected))
}

Tokens are embedded in forms and HTMX headers. hmac.Equal prevents timing attacks.

In-Memory Rate Limiting

Public API limits requests to 10 per minute per IP, without external storage:

Google AdInline article slot
type IPLimiter struct {
    visitors sync.Map
    mu       sync.Mutex
}

type entry struct {
    count   int
    resetAt time.Time
}

func (l *IPLimiter) Allow(ip string) bool {
    now := time.Now()
    val, _ := l.visitors.LoadOrStore(ip, &entry{resetAt: now.Add(time.Minute)})
    e := val.(*entry)

    l.mu.Lock()
    defer l.mu.Unlock()

    if now.After(e.resetAt) {
        e.count = 0
        e.resetAt = now.Add(time.Minute)
    }
    if e.count >= 10 {
        return false
    }
    e.count++
    return true
}

sync.Map with cleanup every 5 minutes.

First Run Without Configuration

The server auto-initializes the database, generates an admin password, and prints it to console. Configuration via flags or environment variables:

  • ./cms — defaults (port=8080, db=./cms.db)
  • CMS_PORT=8080 CMS_DB_PATH=./data.db ./cms

Security Measures

| Threat | Mitigation |

|--------|------------|

| SQL injection | Parameterized queries |

| XSS | html/template with automatic escaping |

| CSRF | HMAC tokens |

| Brute force | Rate limit at 10 req/min |

| Path traversal | http.FileServer in sandbox |

Key Highlights:

  • Binary ~20 MB with static assets via embed.FS, zero runtime dependencies
  • WAL SQLite for concurrency without locks
  • Go channels instead of Redis/Celery queues
  • HMAC CSRF + html/template for robust security
  • CGO_ENABLED=0 — cross-compilation from Windows to Linux

— Editorial Team

Advertisement 728x90

Read Next