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.
cd services/comments
go vet ./...
go test -count=1 ./...
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.
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o codertronix-comments .
file codertronix-comments
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:
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.
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;
All four API blocks include one shared snippet, which holds the actual proxy settings:
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":
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:
COMMENTS_ADMIN_TOKEN=test-token-123 ./codertronix-comments
echo $?
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:
// 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:
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
}
What each check is for:
- The service only accepts JSON. Requiring
application/jsonmeans a plain HTML form on another site can't post here, because forms can't send that content type without JavaScript.mime.ParseMediaTypeacceptsapplication/json; charset=utf-8as well. - It checks
Sec-Fetch-Site. Modern browsers add this header to requests sent to secure origins, which includes any HTTPS site. If it sayscross-site, a page on another domain made the call, and the service refuses it. A request without the header, such as one from curl, is allowed, because the header is only a browser signal. - Request bodies are capped at 32 KiB. The Go docs describe
http.MaxBytesReaderas being for "limiting the size of incoming request bodies". It returns a*http.MaxBytesErroronce the limit is crossed, and the handler turns that into a 413. 32 KiB leaves room for 4,000 non-ASCII characters plus the other fields. - A honeypot field catches simple bots. The form contains a
websiteinput that people never see. Simple bots fill every field. When it is filled, the service answers exactly as if the comment had been accepted and stores nothing, so the bot learns nothing. - Only known slugs get comments. The slug has to match
^[a-z0-9][a-z0-9\-]{0,80}$. IfCOMMENTS_ALLOWED_SLUGS_DIRis set, it also has to be the name of an.htmlfile in that directory. In production that is the posts folder of the webroot, so nobody can create comment threads for pages that don't exist. The list is loaded at startup and reloaded every hour. - Lengths are counted in characters. The name is limited to 64 characters, the body to 2 to 4,000, and the email to 254. They are counted with
utf8.RuneCountInString, so a Hindi or emoji comment gets the same limit as an English one. Control characters other than newline and tab are stripped first. - A body with more than two links, counted by
http://andhttps://, is rejected as "too many links". The first version counted the bare word "http", which I come back to below. - Each IP may submit 5 comments per 10 minutes. The limiter is a map of timestamps per IP, and the hourly job sweeps out IPs with no recent hits, so the map can't grow forever. It runs after validation, so a rejected request doesn't use up the budget.
- The moderation queue is capped. If 1,000 comments are already waiting for moderation, new ones get a 503. A flood can fill the queue but can't fill the disk.
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:
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"
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:
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"
And the per-IP limit. Every request in this loop is valid, so each one counts:
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
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:
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:
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}'
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:
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 .
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.
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:
[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=64What each line does, checked against the systemd.exec man page:
EnvironmentFile: loads the token and the slug directory. systemd reads this file itself, as root, just before starting the process. So the file can be mode 0600 and owned by root, and the service user never needs read access to it.Restart=on-failure,RestartSec=2: restart the process if it crashes, but not after a clean stop.NoNewPrivileges: the process and its children can never gain privileges throughexecve(), so setuid binaries and file capabilities do nothing for them.PrivateTmp: gives the service its own/tmpand/var/tmp, invisible to other processes and emptied when it stops.ProtectSystem=strict: makes the whole filesystem read-only for the service, except/dev,/procand/sys, which other options below lock down.ReadWritePaths: carves out the one exception: the data directory wherecomments.jsonandcontact.jsonlive.ReadOnlyPaths: names the posts folder the slug list is read from. Understrictit is read-only already, so this line is mostly documentation. It also keeps the folder read-only if I ever relaxProtectSystem.ProtectHome: makes/home,/rootand/run/userempty and inaccessible, so SSH keys and shell histories are out of reach.ProtectKernelTunables: makes/proc/sys,/sysand similar kernel settings read-only.ProtectKernelModules: blocks loading or unloading kernel modules.ProtectControlGroups: makes/sys/fs/cgroupread-only, so the service can't change its own resource limits.PrivateDevices: gives it a minimal/devwith only pseudo devices such as/dev/nulland/dev/random, and no disks.RestrictAddressFamilies: limits which kinds of sockets it can create to Unix, IPv4 and IPv6. That rules out raw packet sockets, netlink and the rest.RestrictNamespaces: forbids creating or entering namespaces, which many container-escape and sandbox tricks depend on.LockPersonality: stops the process from changing its execution domain withpersonality(2).MemoryDenyWriteExecute: refuses memory that is both writable and executable. That breaks JIT compilers, but Go compiles ahead of time, so the service runs normally with it.SystemCallArchitectures=native: allows only x86-64 system calls, so 32-bit calls can't be used to slip past the filter.SystemCallFilter: appears twice. The first line allows@system-service, the set the man page calls "the recommended starting point" for services. The second line, with~, takes@privileged(calls that need superuser capabilities) and@resources(calls that change limits and scheduling) back out. A forbidden call kills the process with SIGSYS.LimitNOFILE=4096: sets both the soft and hard limit for open files. Go needs this: since Go 1.19, programs that importosraise their soft limit to the hard limit at startup. Setting both to 4096 gives a real ceiling.MemoryMax=128M,TasksMax=64: are cgroup limits: a hard memory ceiling and a cap on threads. A leak or a runaway loop hits these instead of the rest of the server.

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".
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
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:
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.envopenssl 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:
// 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:
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.

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:
jq '.[] | select(.approved) | {id, name, approved, ip, ua, email}' data/comments.json
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:
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:
curl -s -D - "https://codertronix.com/api/comments?slug=go-concurrency-patterns"
curl -s -w " [%{http_code}]\n" https://codertronix.com/api/comments/admin
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.
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
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:
- The startup log reports how many slugs it loaded, but the hourly reload is silent when it succeeds, so I can't tell from the journal when a new post became commentable. Logging a line only when the count changes would fix that.
writeFileAtomicsyncs the file but not the directory that holds it. After a power cut at exactly the wrong moment, some filesystems can lose the rename. Opening the directory and callingSyncon it after the rename is a few lines.systemd-analyze securitystill lists unset options, includingCapabilityBoundingSet=,ProtectClock,ProtectKernelLogs,ProtectHostname,RestrictSUIDSGID,RestrictRealtime,UMaskandIPAddressDeny. The service needs none of the capabilities those cover, so most should be safe to add. I'd add them one at a time and restart after each.- The service's log lines include client IPs, and they live in the systemd journal, which on this server uses journald's default size-based limits, not the 30-day rule. They are server logs, which the privacy policy covers separately, but a cleaner design would log a truncated IP.
/api/comments/healthis reachable through the public location and returns the start time and uptime. That is harmless, but nobody outside needs it, so it could move under the loopback-only rule.
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
- The service binds to
127.0.0.1, and nothing else listens on its port. - Admin paths are a longer nginx prefix with
allow 127.0.0.1; allow ::1; deny all;, and the service checks a header token as well. - The token is at least 24 characters, lives in a 0600 root-owned env file, and is only ever sent as a header.
X-Real-IPis set by nginx and trusted only from loopback, with the proxy secret.- Every
http.Servertimeout is set, and request bodies go throughhttp.MaxBytesReader. - Writes go to a temp file, are fsynced, then renamed. Memory changes only after the disk write succeeds.
- Non-GET requests sent as TLS early data get a 425.
- Honeypot, slug allow-list, length limits in characters, per-IP limit and a queue cap all run before anything is stored.
- Nginx rate-limits first, and its 429/502/504 responses are JSON, because the widget parses JSON.
- The unit runs as a nologin user with
ProtectSystem=strictand oneReadWritePaths, andsystemd-analyze securityhas been run on it. - Retention runs inside the service at startup and every hour, and matches the retention periods in the privacy policy.
- From outside, the public list returns JSON with
no-store, and the admin path returns nginx's 403.



