A Static Site That Needed a Backend Anyway

Codertronix is plain HTML, CSS and JavaScript. Nginx serves files from disk and there is no build step. That covers almost everything a tutorial site does, because almost everything is reading.

Two features break that model. Comments under each post and the contact form both accept text from strangers, and a folder of static files can't store it. Something has to receive the request, check it, write it somewhere and serve it back later.

I didn't want a hosted comment widget. That would mean loading someone else's script on every post and sending readers' names and IP addresses to a company they never chose to deal with. The header of js/comments.js says what I wanted instead: "self-hosted, no third-party". So I wrote a small service in Go. It lives in services/comments/ in the site's repository: main.go for comments, contact.go for the contact form, two test files and a systemd unit.

This post is how that service is built and why each piece is the way it is. Every snippet is copied from the real files (some are shortened where marked), and every screenshot is real output: either from a copy of the service I ran locally while writing this, or from read-only checks against the live site.

Why Go, and Why Only the Standard Library

The service needs to parse JSON, validate a few fields, keep a rate limit, write a file and answer HTTP. Go's standard library has all of that. go.mod declares go 1.22 and has no require lines at all, so there are no third-party modules to audit, update or get surprised by.

The second reason is deployment. A Go program cross-compiles to one static binary. I build it on Windows, copy one file to the server and restart the unit. The server needs no Go toolchain, no language runtime and no package manager for it.

Before building, I run vet and the tests. There are 18 tests between main_test.go and contact_test.go. They cover the submit-then-approve flow, the admin header, the rejections, the link count, the proxy secret, the honeypot, the rate limiter, the retention pass and a failed save. They run against httptest, so they never open a port.

terminal
cd services/comments
go vet ./...
go test -count=1 ./...
Terminal: go version prints go1.27.0 windows/amd64, go vet ./... prints nothing, go test -count=1 ./... prints ok codertronix-comments 0.734s.
Real output. go vet reports nothing and all 18 tests pass in services/comments, including the link-count and proxy-secret tests.

The build for the server is a single command. On Windows in PowerShell you set $env:GOOS='linux' and $env:GOARCH='amd64' first. In Git Bash, as below, you can put them in front of the command. The Go docs say cgo is already off by default when cross-compiling, but I set CGO_ENABLED=0 anyway so the result never depends on whether a C compiler happens to be installed.

terminal
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o codertronix-comments .
file codertronix-comments
Terminal: GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build, file reports an ELF 64-bit statically linked executable, du shows 9.9M, grep -c require go.mod prints 0.
Real output. A Linux build from Windows: one statically linked ELF file, 9.9 MB, and go.mod has no require lines.

The binary is 9.9 MB with debug information. Building with -ldflags="-s -w" took it to 7,053,472 bytes when I tried it. I ship the normal build, because size doesn't matter for a single file on a server and the symbols help if I ever have to read a stack trace.

Listening on Loopback and Letting Nginx Face the Internet

The service listens on 127.0.0.1:8088, which is the default of COMMENTS_LISTEN. Nothing outside the machine can connect to that address. The only public entry point is nginx, which already handles TLS, HTTP/2, compression and logging for the rest of the site. The nginx configuration guide covers reverse proxying in general. Here is the part of the site config that routes the API:

nginx/sites-available/codertronix.com.conf
location ^~ /api/comments/admin {
    allow           127.0.0.1;
    allow           ::1;
    deny            all;
    include         /etc/nginx/snippets/comments-proxy.conf;
}
location ^~ /api/comments {
    limit_req       zone=comments_api burst=20 nodelay;
    limit_conn      perip 20;
    include         /etc/nginx/snippets/comments-proxy.conf;
}

Both blocks are prefix locations, and nginx picks the longest matching prefix. A request for /api/comments/admin/approve matches both, and the longer /api/comments/admin wins. That block allows only loopback addresses, so from the internet every admin path gets a 403 from nginx itself. The request never reaches Go. The ^~ modifier tells nginx to skip regular-expression locations once it has picked a prefix, so none of the site's regex rules for static files can take over an API path.

Public requests go through the second block, where two limits apply. The comments_api zone in nginx.conf allows 10 requests per second per client address, with a burst of 20. limit_conn perip 20 caps open connections per address. The contact form has its own location = /api/contact block with burst=5, limit_conn perip 10 and client_max_body_size 32k, and its admin path is restricted to loopback in the same way.

nginx/nginx.conf
limit_req_zone  $binary_remote_addr zone=comments_api:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_req_status  429;
limit_conn_status 429;
Table of six requests and the nginx location that answers each: public GET and POST on /api/comments are rate-limited and proxied to port 8088; /api/comments/admin and /api/contact/admin from the internet get 403 from nginx; the same admin path from 127.0.0.1 is proxied and the token is checked; POST /api/contact has burst=5, 10 connections and a 32k body limit.
How nginx routes each API path. The admin blocks are longer prefixes, so they win over the public block for any path under /admin.

All four API blocks include one shared snippet, which holds the actual proxy settings:

nginx/snippets/comments-proxy.conf
include            /etc/nginx/snippets/security-headers.conf;
proxy_pass         http://127.0.0.1:8088;
proxy_http_version 1.1;
proxy_set_header   Host              $host;
# Trusted only from loopback, and only with the secret from the root-only file below.
proxy_set_header   X-Real-IP         $remote_addr;
include            /etc/nginx/private/comments-proxy-secret*.conf;
proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
proxy_set_header   X-Forwarded-Proto $scheme;
proxy_set_header   X-Request-ID      $request_id_final;
proxy_set_header   Early-Data        $ssl_early_data;
proxy_read_timeout    10s;
proxy_send_timeout    10s;
proxy_connect_timeout 5s;
error_page 429     = @comments_429;
error_page 502 504 = @comments_503;

Three of those lines need explaining.

Behind a proxy, every connection the service sees comes from 127.0.0.1. The visitor's real address arrives in X-Real-IP, and nginx always overwrites that header with $remote_addr, so a visitor can't forge it. The Go side only believes the header when the TCP peer is a loopback address and the request also carries a shared secret that nginx adds. A request that reached the port some other way would be judged by its real source address.

The site has TLS 1.3 0-RTT turned on for faster repeat visits. Early data can be replayed by an attacker, which is harmless for a GET of a static page but not for a POST that stores a comment. When a request arrives as early data, nginx passes Early-Data: 1. The service then answers any non-GET, non-HEAD request with 425 Too Early, the status RFC 8470 defines for this, and the client retries after the full handshake.

The widget expects JSON. If nginx rate-limits a request or the service is down, nginx would normally send its HTML error page. The two error_page lines send those cases to named locations that return small JSON bodies such as {"error":"slow down"} with Retry-After. Errors produced by the service itself are already JSON and pass through unchanged.

On the Go side, the server is a plain http.Server with every timeout set, because the zero values mean "no timeout":

services/comments/main.go
httpSrv := &http.Server{
    Addr:              listen,
    Handler:           srv.routes(),
    ReadHeaderTimeout: 5 * time.Second,
    ReadTimeout:       15 * time.Second,
    WriteTimeout:      15 * time.Second,
    IdleTimeout:       60 * time.Second,
    MaxHeaderBytes:    1 << 16,
}

MaxHeaderBytes is 64 KiB instead of the 1 MB default. On SIGTERM a goroutine calls Shutdown with a five-second deadline, so a systemctl restart lets requests in flight finish. Routes are registered with http.NewServeMux as exact paths such as /api/comments and /api/comments/admin/approve. Patterns without a trailing slash match only that exact path, and a catch-all / returns a JSON 404. Each handler checks the method itself and sends an Allow header when it refuses one.

The process also refuses to start without a usable admin token. Here it is with the obviously fake test-token-123, which is too short, and then with a longer fake token and data and slug directories inside my scratch folder:

terminal
COMMENTS_ADMIN_TOKEN=test-token-123 ./codertronix-comments
echo $?
Terminal: the service exits with COMMENTS_ADMIN_TOKEN is required and must be >= 24 chars and status 2, then starts with a longer token and logs loaded 37 allowed slugs and listening on 127.0.0.1:8088.
Real output. A 14-character token is refused with exit code 2. With a 32-character fake token the service loads the slug list and listens on 127.0.0.1:8088.

Storage: One JSON File, Rewritten Atomically

Comments live in one file, /var/lib/codertronix-comments/comments.json. It is a JSON array of records loaded into memory at startup. A site with 37 posts and moderated comments will not outgrow that for a long time, and a JSON file can be read with jq, backed up with cp and fixed with a text editor. I wanted that more than I wanted a database.

The risk with a single file is a half-written file after a crash. Every change goes through the same two functions:

services/comments/main.go
// writeFileAtomic writes to a temp file, fsyncs it, then renames it over path.
func writeFileAtomic(path string, data []byte) error {
    tmp := path + ".tmp"
    f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o640)
    // ... write, f.Sync(), f.Close(); on any error remove tmp and return
    return os.Rename(tmp, path)
}

// commitLocked persists next and, only if that succeeds, makes it the live data.
func (s *store) commitLocked(next []Comment) error {
    b, err := json.MarshalIndent(next, "", "  ")
    if err != nil {
        return err
    }
    if err := writeFileAtomic(s.path, b); err != nil {
        return err
    }
    s.comments = next
    return nil
}

On Linux, rename(2) replaces the target atomically, so a reader sees either the old file or the new one, never a mix. Inside commitLocked, the order is deliberate. The new slice is built as a copy, written to disk, and only then swapped in. If the disk write fails, memory still matches what is on disk. One test, TestFailedSaveKeepsMemoryConsistent, checks exactly that.

A single sync.Mutex guards the store. Every write rewrites the whole file, which is fine at this size and keeps the code short. Comment IDs are 12 bytes from crypto/rand, hex-encoded to 24 characters, and the admin routes reject any id that doesn't match ^[0-9a-f]{24}$.

What Happens to a Comment

A POST to /api/comments carries JSON with slug, name, an optional email, body and a website field that should be empty. Here is the handler in order, shortened:

services/comments/main.go
if mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || mt != "application/json" {
    writeErr(w, http.StatusUnsupportedMediaType, "content type must be application/json")
    return
}
// Browsers send Sec-Fetch-Site; refuse submissions made by other sites.
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
    writeErr(w, http.StatusForbidden, "cross-site submissions are not allowed")
    return
}
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBytes)
// ... decode; a *http.MaxBytesError becomes 413 "comment too long"
if in.Website != "" {
    // honeypot: pretend success but don't store.
    writeJSON(w, http.StatusAccepted, map[string]any{"status": "pending"})
    return
}
// ... slugAllowed, name and body length, email length, link count
ip := clientIP(r)
if !s.limiter.allow(ip, s.now()) {
    writeErr(w, http.StatusTooManyRequests, "slow down")
    return
}
Ten numbered checks with the status each returns: early data 425, wrong content type 415, cross-site 403, body over 32 KiB 413, honeypot 202 with nothing saved, unknown slug 400, length limits 400, more than two http 400, over five per IP in ten minutes 429, 1000 pending 503; a comment that passes all of them is saved as pending with 202.
Every check between a POST and the file, in the order the code runs them. The early-data check is middleware that runs before the handler.

What each check is for:

Everything that passes is saved with approved: false and the visitor gets a 202 with "Thanks! Your comment is awaiting moderation." Nothing appears on the page until I approve it. Here is the public side, run against my local copy, with API set to http://127.0.0.1:8088/api/comments:

terminal
export API=http://127.0.0.1:8088/api/comments
curl -s "$API?slug=go-concurrency-patterns"
curl -s -X POST -H 'Content-Type: application/json' \
  -d '{"slug":"go-concurrency-patterns","name":"Test Reader","email":"reader@example.com","body":"..."}' "$API"
Terminal: GET returns count 0, POST returns awaiting moderation, POST for slug wp-login returns unknown post 400, GET with slug ../etc/passwd returns invalid slug 400.
Real output. Listing an empty post, posting a comment (202, pending), a slug that is not a post, and a slug that fails the regex.

The wp-login slug is the kind of path scanners try. It fails because there is no wp-login.html in the slug directory. The ../etc/passwd slug never gets that far, because it fails the regex. Then each of the other guards, one at a time:

terminal
J='Content-Type: application/json'
curl -s -w '%{http_code}\n' -X POST -H "$J" -H 'Sec-Fetch-Site: cross-site' -d '{...}' "$API"
curl -s -w '%{http_code}\n' -X POST -H "$J" -H 'Early-Data: 1' -d '{...}' "$API"
curl -s -w '%{http_code}\n' -X POST -H "$J" --data-binary @big.json "$API"
Terminal: honeypot returns 202 pending, three links 400, Sec-Fetch-Site cross-site 403, form-encoded body 415, Early-Data 425, 40062-byte body 413 comment too long.
Real output. Each guard answering on its own: honeypot (fake 202), too many links, cross-site, form encoding, TLS early data, and a 40 KB body.

And the per-IP limit. Every request in this loop is valid, so each one counts:

terminal
for i in 1 2 3 4 5; do
  curl -s -o /dev/null -w "$i %{http_code}\n" -X POST -H 'Content-Type: application/json' \
    -d "{\"slug\":\"nginx-configuration\",\"name\":\"Loop\",\"body\":\"rate test $i\"}" "$API"
done
Terminal: a loop posts five comments; responses are 202, 202, 202, 202, 429.
Real output. Five valid comments from one IP inside a minute: four were accepted (the first test comment had already used one slot), the fifth got 429.

There are two rate limits on purpose. Nginx's 10 requests per second stops floods before they cost the Go process anything. The service's 5 per 10 minutes is about behaviour: no real reader writes six comments in ten minutes. The service's limiter lives in memory, so a restart resets it. I accept that, because nginx still applies its own limit across restarts.

Moderation Over an SSH Tunnel

The admin API has three routes: GET /api/comments/admin lists pending comments, and POST /api/comments/admin/approve?id=... and /delete?id=... act on one. I didn't build an admin web page, because a page would need a login, and a login is one more thing to secure. I moderate with curl through SSH:

terminal
ssh -N -L 8088:127.0.0.1:8088 <user>@<server>     # in one terminal
TOKEN=...                                         # value from /etc/codertronix-comments.env
curl -s -H "X-Admin-Token: $TOKEN" http://127.0.0.1:8088/api/comments/admin
curl -s -X POST -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:8088/api/comments/admin/approve?id=<id>"

The tunnel makes port 8088 on my laptop forward to port 8088 on the server's loopback, and SSH keys already protect that path. Requests through the tunnel go straight to the Go process, not through nginx. That's why the service checks a token of its own as well as nginx's loopback rule. Either layer alone would stop an outsider, and having both means one mistake in a config file doesn't expose moderation.

Here is the admin side on my local copy, with the fake token in TOKEN. The token has to arrive in the X-Admin-Token header. In the query string it is ignored:

terminal
export TOKEN=test-token-123-not-a-real-secret
curl -s -w '%{http_code}\n' "$API/admin"
curl -s -w '%{http_code}\n' "$API/admin?token=$TOKEN"
curl -s -H "X-Admin-Token: $TOKEN" "$API/admin" | jq '.pending[] | {id, slug, name, approved, ip, ua, email}'
Terminal: admin without token 403 forbidden, admin with ?token= 403 forbidden, admin with X-Admin-Token header returns the pending comment including ip 127.0.0.1, ua curl and email.
Real output. No token gets 403, a token in the query string also gets 403, and the X-Admin-Token header lists the pending comment with its private fields.

The admin list is the only place the private fields appear: IP, user agent and email. Approving needs a POST, so a link or a prefetch can't approve anything by accident:

terminal
ID=88c31c474272d1de546fed87
curl -s -w '%{http_code}\n' -H "X-Admin-Token: $TOKEN" "$API/admin/approve?id=$ID"
curl -s -X POST -H "X-Admin-Token: $TOKEN" "$API/admin/approve?id=$ID"
curl -s "$API?slug=go-concurrency-patterns" | jq .
Terminal: GET on approve returns 405, POST returns status approved, then the public list returns one comment with id, slug, name, body, created_at and approved true.
Real output. Approve only accepts POST. After approval the public list shows the comment, without IP, user agent or email.

For the public list, each comment is copied into a separate publicComment struct that has no IP, user agent or email fields at all, so those can't leak through a forgotten omitempty. The public list returns at most the newest 500 approved comments for a post, oldest first.

The Browser Widget

js/comments.js mounts on any page that has <div id="comments" data-slug="...">. It is unhashed and gets a short cache lifetime, so a fix reaches readers quickly. It does two things before it draws anything.

js/comments.js
function start() {
  requestJSON(endpoint + "?slug=" + encodeURIComponent(slug), { credentials: "omit" })
    .then(function (data) {
      build();
      fill(data);
    })
    .catch(function (err) {
      dropSection((err && err.message) || "unavailable");
    });
}

// Don't hit the API from a speculative prerender; wait until the page is shown.
if (document.prerendering) {
  document.addEventListener("prerenderingchange", start, { once: true });
} else {
  start();
}

First, it asks the API for the comment list. If the service is down, it removes the whole comments section, so a reader sees a normal page with no comments instead of a broken form. Second, the site uses speculation rules to prerender posts a reader is likely to open. Without the document.prerendering check, every prerender would call the API for a page the reader might never view.

Comments are rendered safely. Names and dates are set with textContent. The body is HTML-escaped first, and the only markup added afterwards is <br> for line breaks. The form checks the same limits as the server, counted in code points with Array.from(s).length to match Go's rune count. That way a reader learns about a long comment before sending it, but the server still decides. Requests use credentials: "omit", because the API has no cookies and needs none. Error statuses are turned into plain messages: 429 becomes "You're posting too fast", any 5xx or non-JSON reply becomes "temporarily unavailable", and 403, 415 and 425 become a generic "please reload and try again".

The systemd Unit, Line by Line

The service runs as codercmt, a system user created with useradd --system --no-create-home --shell /usr/sbin/nologin. Nobody can log in as that user, and it owns exactly one directory. The unit file then removes most of what that user could otherwise touch:

services/comments/systemd/codertronix-comments.service
[Service]
Type=simple
User=codercmt
Group=codercmt
EnvironmentFile=/etc/codertronix-comments.env
ExecStart=/usr/local/bin/codertronix-comments
Restart=on-failure
RestartSec=2
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/lib/codertronix-comments
ReadOnlyPaths=/var/www/codertronix.com/posts
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
PrivateDevices=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=yes
LockPersonality=yes
MemoryDenyWriteExecute=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources
LimitNOFILE=4096
MemoryMax=128M
TasksMax=64

What each line does, checked against the systemd.exec man page:

Left: eight filesystem areas and what the service can do there. /var/lib/codertronix-comments is read-write, the posts folder, /usr, /etc, /proc/sys, /sys and /sys/fs/cgroup are read-only, /home, /root and /run/user are inaccessible, /tmp is a private copy and /dev has pseudo devices only. Right: process limits including User=codercmt, NoNewPrivileges, MemoryMax=128M, TasksMax=64, LimitNOFILE=4096, the system call filter and allowed address families.
What the unit leaves the service able to touch. One directory is writable and the rest is read-only or hidden.

Here is the live unit, checked with read-only commands on the server (hostname removed). The status line shows the limits in effect: 7.7 MB of memory against the 128 MB cap and 8 tasks against 64. systemd-analyze security, which scores sandboxing from 0 (locked down) to 10 (fully exposed), rates it 4.0 and labels that "OK".

terminal (server, read-only)
systemctl status codertronix-comments --no-pager -n 0
sudo stat -c "%A %U:%G %n" /etc/codertronix-comments.env /var/lib/codertronix-comments
systemd-analyze security codertronix-comments --no-pager | tail -1
Terminal: systemctl status shows active (running) since 27 October with Memory 7.7M of max 128M and Tasks 8 of limit 64; stat shows the env file -rw------- root:root; getent shows /usr/sbin/nologin; local admin without token 403; systemd-analyze exposure 4.0 OK.
Real output. On the server: the unit is running inside its limits, the env file is root-only, the service user has no login shell, and systemd-analyze rates the unit 4.0 OK.

The Admin Token

The token is generated on the server and goes straight into the root-only env file, so it never passes through the repository or my clipboard:

terminal (server)
printf 'COMMENTS_ADMIN_TOKEN=%s\nCOMMENTS_ALLOWED_SLUGS_DIR=/var/www/codertronix.com/posts\n' \
    "$(openssl rand -hex 32)" | sudo install -m 0600 /dev/stdin /etc/codertronix-comments.env

openssl rand -hex 32 gives 64 hex characters. The service refuses to start with fewer than 24, which catches a leftover placeholder before it reaches production. The check itself is short:

services/comments/main.go
// requireAdmin checks the X-Admin-Token header in constant time.
func (s *server) requireAdmin(w http.ResponseWriter, r *http.Request) bool {
    tok := r.Header.Get("X-Admin-Token")
    if tok == "" || subtle.ConstantTimeCompare([]byte(tok), s.adminToken) != 1 {
        writeErr(w, http.StatusForbidden, "forbidden")
        return false
    }
    return true
}

subtle.ConstantTimeCompare takes the same time no matter where two equal-length tokens first differ, so response timing doesn't reveal the token one character at a time. Its docs note that it returns immediately when the lengths differ. That leaks only the length, and the length of a 32-byte hex token isn't a secret.

I only accept the token in a header because query strings get written down in many places: the nginx access log format on this server records $request, which includes the query string, and shell history and browser history keep full URLs too. A header is not logged by any of those by default. The service's own log line records the client IP, method, path, status and duration, and deliberately never the query string, because that is where comment IDs go.

Privacy and Retention

The privacy policy promises two things about comments: comments that are never approved are deleted after 30 days, and approved comments lose their IP address, user agent and email 30 days after posting. Name and text stay public until someone asks for removal. The service enforces this itself instead of relying on a cron job I might forget to install:

services/comments/main.go
func (s *store) prune(now time.Time, maxAge time.Duration) (int, error) {
    // ...
    cutoff := now.Add(-maxAge)
    for _, c := range s.comments {
        if !c.CreatedAt.Before(cutoff) {
            next = append(next, c)
            continue
        }
        if !c.Approved {
            changed++
            continue
        }
        if c.IP != "" || c.UA != "" || c.Email != "" {
            c.IP, c.UA, c.Email = "", "", ""
            changed++
        }
        next = append(next, c)
    }
    // ...
}

janitorOnce calls prune with a 30-day retention constant. It runs once at startup and then every hour from a time.Ticker. The same pass sweeps the rate limiter, applies the contact form's 90-day rule and reloads the slug list. Because it also runs at startup, a service that was down for a week catches up as soon as it comes back.

Timeline from day 0 to day 90 for three record types. A pending comment is hidden from the public list and is deleted at 30 days unless approved. An approved comment shows name, body and created_at publicly and keeps ip, ua and email privately until day 30, when those three are erased. A contact message is never public and is deleted at day 90.
What each record keeps over time. The hourly janitor applies these rules; the timeline is not to scale.

I keep IP and user agent at first because, while a comment waits for moderation, they help me spot one sender posting under several names. Once a comment has been public for a month, they serve no purpose, so they go. Here is the stored record of my test comment on day 0, still holding all three:

terminal
jq '.[] | select(.approved) | {id, name, approved, ip, ua, email}' data/comments.json
Terminal: jq on data/comments.json shows the approved comment with ip 127.0.0.1, ua curl/8.21.0 and email reader@example.com.
Real output. The stored record of the approved test comment still holds IP, user agent and email until the 30-day retention pass erases them.

The test TestRetention seeds the store with comments dated 31 days back and checks both halves of the rule: the old pending comment is gone, the old approved one is still there with empty private fields, a new pending comment is untouched, and the result survives a reload from disk.

The Contact Form Uses the Same Service

contact.go adds POST /api/contact to the same process instead of running a second one. It reuses the same pieces: sanitize, the honeypot, the JSON and Sec-Fetch-Site checks, MaxBytesReader at 32 KiB, writeFileAtomic and the admin header. Messages go to their own file, contact.json next to the comments, and are never shown publicly. They have their own rules:

services/comments/contact.go
if a, err := mail.ParseAddress(in.Email); err != nil || a.Address != in.Email || utf8.RuneCountInString(in.Email) > maxEmailLen {
    writeErr(w, http.StatusBadRequest, "Please enter a valid email address so I can reply.")
    return
}

Email is required here, because the point of a contact form is a reply. Comparing a.Address with the input rejects strings that net/mail would accept but that aren't a bare address, such as Name <x@y.z>. The subject is limited to 150 characters with newlines flattened. The message must be 10 to 5,000 characters with no more than 3 links. There is a separate per-IP limiter, so a busy comment thread can't use up someone's budget for writing to me. At most 2,000 messages are stored, and anything older than 90 days is deleted by the same hourly job. I read messages through GET /api/contact/admin over the same tunnel, and nginx keeps that path loopback-only like the comment admin routes.

Checking It From Outside

Local tests say the code works. They don't say that nginx routes correctly in production. These two checks run from my own machine against the live site. Both are read-only GETs:

terminal
curl -s -D - "https://codertronix.com/api/comments?slug=go-concurrency-patterns"
curl -s -w " [%{http_code}]\n" https://codertronix.com/api/comments/admin
Terminal: curl to https://codertronix.com/api/comments returns 200 application/json with Cache-Control no-store and an empty list; /api/comments/admin returns an nginx 403 Forbidden HTML page.
Real output. From my machine: the public list answers as JSON with no-store, and the admin path gets nginx's own 403 page.

The first should return JSON with Cache-Control: no-store, so no browser or proxy keeps a stale comment list. The second must be a 403, and it should be nginx's own HTML page, not the service's JSON {"error":"forbidden"}. The HTML page is how I know nginx refused the request before Go ever saw it. X-Content-Type-Options appears twice in the real output, because both the service and nginx's security-headers snippet set it. It does no harm, and I only noticed it by reading the real headers.

Two Things I Found While Testing It

Running every endpoint by hand for this post turned up two behaviours the tests didn't cover. I fixed both before publishing.

terminal
curl -s -w '%{http_code}\n' -X POST -H 'Content-Type: application/json' -H 'X-Real-IP: 192.0.2.50' \
  -d '{"slug":"nginx-configuration","name":"Reader","body":"Does this work over HTTP/1.1, HTTP/2 and HTTP/3?"}' "$API"
tail -n 1 server.log
Terminal: a comment mentioning HTTP/1.1, HTTP/2 and HTTP/3 returns too many links 400; the last log line shows the request logged as coming from 192.0.2.50.
Real output. Before the fix: a comment that only mentions HTTP versions is rejected as too many links, and X-Real-IP sent from loopback is believed.

The first problem was that the link check counted the word "http". strings.Count(strings.ToLower(in.Body), "http") saw three matches in "HTTP/1.1, HTTP/2 and HTTP/3" and rejected a normal question with "too many links". On a site full of nginx and HTTP tutorials, readers will write that. I changed it to count http:// and https:// instead, added a test with that sentence, and deployed the fix on 18 November. The same request now gets a 202, and a body with three real links still gets a 400.

The second was that any local process could choose the logged IP. The last log line shows the request recorded as coming from 192.0.2.50, the address I put in X-Real-IP, because my curl ran on the same machine and so counted as loopback. In production that needs shell access to the server, and nginx overwrites the header for every outside request, so it wasn't a hole. But it meant the rate limit trusted every process on the box, not only nginx. Now nginx adds an X-Proxy-Auth header from a file only root can read, and the service believes X-Real-IP only when that header matches COMMENTS_PROXY_SECRET. With the secret set, the same curl is logged as 127.0.0.1.

What I Would Change

When I checked on 17 November, the service had been running since 27 October without a restart, using under 8 MB of memory. The design holds up, but I would still change a few things:

What I would not change is the overall shape: one binary, one file, loopback only, nginx in front, and moderation over SSH. If you want the Go side of something like this, the Go concurrency guide covers the mutexes, goroutines and tickers this service relies on. For the server underneath it, see what broke when I deployed this site to EC2.

Checklist

AS

Anurag Sinha

Founder & Lead Developer

Anurag is a full stack developer and self-taught programmer from India with over five years of experience building web applications, APIs, and cloud-native systems. He researches, writes and reviews every tutorial on Codertronix, and updates them when the tools change.