Stop form spam in Go

Updated

This guide adds Bot403 to a contact form in a Go server that uses only net/http. The browser solves a small proof of work. Then a middleware checks the token with one call to the verify API, before your handler runs. The visitor sees no puzzle, and the script sets no cookie. The free plan covers 5,000 checks a month and needs no card.

The example needs Go 1.25 or newer, for http.CrossOriginProtection, and no module outside the standard library. On 12 November 2026, the code on this page ran on Go 1.27.4 against a local stand-in for the verify API that gives the documented answers, and in Chrome 157 with the Bot403 browser script. A good token went through. A reused token, a filled honeypot and a form with no token were refused. When the API did not answer, or took longer than 5 seconds, the form went through and the server logged a warning.

Before you start

Sign in. Create a site. Copy its public key (pk_) and its secret key (sk_). Put the secret key in an environment variable, never in your code or your repository.

Terminal
mkdir contact && cd contact
go mod init contact
export BOT403_SECRET_KEY=sk_live_YOUR_SECRET_KEY

The app has this layout:

Layout
contact.html    # the form, embedded in the binary
bot403.go       # the Verifier and its Protect middleware
main.go         # the routes and the server
main_test.go

1. The form

The script tag protects every form on the page. Before the browser sends the form, the script adds a hidden _bot403 field with the token, and a hidden honeypot field (by default _website).

contact.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Contact</title>
  <script src="https://bot403.com/v1/bot403.js" data-bot403-key="pk_live_YOUR_PUBLIC_KEY" async></script>
</head>
<body>
  <form method="post" action="/contact">
    <label>Email <input name="email" type="email" required></label>
    <label>Message <textarea name="message" required></textarea></label>
    <button type="submit">Send</button>
  </form>
</body>
</html>

2. The check

Check posts the whole form to https://bot403.com/api/v1/verify with your secret key. Protect wraps a handler and runs it only when the answer is ok. If Bot403 does not answer, Protect lets the form through and logs a warning. A wrong secret key, a body over 64 KB or too many verify calls a minute give an error and a 500, so you see them and fix them.

bot403.go
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"strings"
)

// errNoAnswer means Bot403 did not answer: a network error or a timeout.
var errNoAnswer = errors.New("bot403 did not answer")

// Verifier checks the token in a submitted form.
type Verifier struct {
	URL    string       // https://bot403.com/api/v1/verify
	Secret string       // the site's secret key, from BOT403_SECRET_KEY
	Client *http.Client // must have a Timeout
}

type result struct {
	OK     bool   `json:"ok"`
	Reason string `json:"reason"`
}

// Check posts the whole form. Bot403 reads the _bot403 field and the honeypot field.
func (v *Verifier) Check(ctx context.Context, form url.Values) (result, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, v.URL, strings.NewReader(form.Encode()))
	if err != nil {
		return result{}, err
	}
	req.Header.Set("Authorization", "Bearer "+v.Secret)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	res, err := v.Client.Do(req)
	if err != nil {
		return result{}, fmt.Errorf("%w: %v", errNoAnswer, err)
	}
	defer res.Body.Close()
	// 200 is an answer, and so is 402 (reason "quota", only in a capped month).
	// 401 wrong key, 413 body over 64 KB, 429 too many calls a minute: fix these.
	if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusPaymentRequired {
		return result{}, fmt.Errorf("bot403 verify: HTTP %d", res.StatusCode)
	}
	var r result
	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		return result{}, fmt.Errorf("bot403 verify: %v", err)
	}
	return r, nil
}

// Protect runs next only for a form that a browser solved.
func (v *Verifier) Protect(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
		// ParseMultipartForm also parses urlencoded forms (then it returns ErrNotMultipart).
		if err := r.ParseMultipartForm(32 << 10); err != nil && !errors.Is(err, http.ErrNotMultipart) {
			http.Error(w, "Form too large or damaged", http.StatusBadRequest)
			return
		}
		res, err := v.Check(r.Context(), r.PostForm) // PostForm: the body only, no query string
		switch {
		case errors.Is(err, errNoAnswer):
			log.Printf("%v, letting the form through", err)
		case err != nil:
			log.Print(err)
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		case !res.OK && res.Reason != "quota":
			http.Error(w, "Try again", http.StatusBadRequest)
			return
		}
		next.ServeHTTP(w, r)
	})
}

A failed token is a normal answer, not an error: ok is false and reason says why. The verify page lists every reason. The answer quota comes only in a capped month, and the example lets the form through then, so a capped month loses no message.

3. The server

The routes use the method patterns of Go 1.22, so GET /contact shows the form and POST /contact goes through Protect. The page is embedded with go:embed, so the binary needs no files next to it.

main.go
package main

import (
	_ "embed"
	"log"
	"net/http"
	"os"
	"time"
)

//go:embed contact.html
var contactPage []byte

func main() {
	secret := os.Getenv("BOT403_SECRET_KEY")
	if secret == "" {
		log.Fatal("set BOT403_SECRET_KEY")
	}
	bot403 := &Verifier{
		URL:    "https://bot403.com/api/v1/verify",
		Secret: secret,
		Client: &http.Client{Timeout: 5 * time.Second},
	}

	mux := http.NewServeMux()
	mux.HandleFunc("GET /contact", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Write(contactPage)
	})
	mux.Handle("POST /contact", bot403.Protect(http.HandlerFunc(contact)))
	mux.HandleFunc("GET /thanks", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Thanks. Your message is on its way."))
	})

	// CrossOriginProtection (Go 1.25) refuses cross-site form posts from browsers.
	csrf := http.NewCrossOriginProtection()
	log.Fatal(http.ListenAndServe(":3000", csrf.Handler(mux)))
}

func contact(w http.ResponseWriter, r *http.Request) {
	// A real visitor: send the email or store the message here.
	log.Printf("message from %s", r.PostForm.Get("email"))
	http.Redirect(w, r, "/thanks", http.StatusSeeOther)
}

The trap: http.DefaultClient has no timeout

Give the verify call its own http.Client with a Timeout. http.DefaultClient, and so http.Post, has a timeout of zero, which the net/http docs define as no timeout. If Bot403 is slow to answer, a handler that uses it waits as long as the connection stays open, and the visitor waits with it.

With Timeout: 5 * time.Second, the call gives up after 5 seconds. In the test run, a stand-in API that waited 30 seconds before it answered got this result: the form went through after 5.0 seconds, and the server logged:

Log
bot403 did not answer: Post "http://127.0.0.1:7811/api/v1/verify": context deadline exceeded (Client.Timeout exceeded while awaiting headers), letting the form through

The request also uses r.Context(). If the visitor closes the page, Go cancels the verify call too.

Why the middleware reads PostForm and calls ParseMultipartForm

Send r.PostForm to Bot403, not r.Form. r.Form also holds the fields of the URL's query string, and r.PostForm holds only the body. In the test run, a token put in the URL (POST /contact?_bot403=…) was not sent, and the form was refused.

Call ParseMultipartForm, not only ParseForm. ParseForm does not read a multipart/form-data body: it returns no error and leaves r.PostForm empty. Then the token never reaches Bot403, and every form with a file input is refused as invalid. ParseMultipartForm parses both kinds of form. For a normal form, it returns http.ErrNotMultipart after it has filled r.PostForm, so the middleware ignores that error. Files are not in r.PostForm, so they never go to Bot403. In the test run, a form with a file sent only _bot403 and email.

The middleware caps the body at 64 KB with http.MaxBytesReader, because the verify API refuses a body over 64 KB with HTTP 413. In the test run, a 70,000-character message got a 400 from Protect. For a form with uploads, raise the cap to the largest upload you accept. ParseMultipartForm(32 << 10) keeps up to 32 KB of the files in memory and writes the rest to temporary files. The text fields still go to Bot403, and they must stay under 64 KB.

CrossOriginProtection does not stop bots

http.CrossOriginProtection (Go 1.25) refuses a form that a browser posts from another site. It reads the Sec-Fetch-Site and Origin headers. A request without either header is allowed, because Go treats it as same-origin or as not from a browser. So it stops other sites from sending forms in the name of your visitor, but a script that posts straight to your server gets through. Bot403 does that job.

In the test run, a POST with Sec-Fetch-Site: cross-site got 403 from CrossOriginProtection. The same POST from curl, without the header, reached Protect, which refused it because it had no token. Keep both.

When the secret key is wrong

A wrong or missing secret key gets HTTP 401 from the verify API. Check turns any status other than 200 or 402 into an error, so Protect answers 500 and logs it:

Log
bot403 verify: HTTP 401

Every form on the site fails until you fix the key, so watch for this line after a deploy. A 429 means too many verify calls for the site this minute: 100 on the free plan.

Forms sent with fetch

If you send the form with fetch, send it as FormData, so the token and the honeypot field go with it. The script listens to the submit event before your own code does. It waits for the token, puts it in the _bot403 field, and then submits again. So when your handler runs, the form already holds the token. A FormData body is multipart/form-data, which is one more reason for ParseMultipartForm.

contact.js
const form = document.querySelector("form");
form.addEventListener("submit", async (event) => {
  event.preventDefault();
  // holds _bot403 and the honeypot field
  const res = await fetch(form.action, { method: "POST", body: new FormData(form) });
  if (res.ok) location.href = res.url;
});

Test it

The tests point the Verifier at an httptest server with a fixed answer, so they need no network and no key:

main_test.go
package main

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"time"
)

// fakeAPI answers every verify call with a fixed status and body.
func fakeAPI(t *testing.T, status int, body string, got *url.Values) *httptest.Server {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		*got = r.PostForm
		w.WriteHeader(status)
		w.Write([]byte(body))
	}))
	t.Cleanup(srv.Close)
	return srv
}

func post(v *Verifier, form url.Values) int {
	h := v.Protect(http.HandlerFunc(contact))
	req := httptest.NewRequest("POST", "/contact", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec.Code
}

func verifier(u string) *Verifier {
	return &Verifier{URL: u, Secret: "sk_test", Client: &http.Client{Timeout: time.Second}}
}

func TestVerifiedFormGoesThrough(t *testing.T) {
	var got url.Values
	api := fakeAPI(t, 200, `{"ok":true}`, &got)
	if code := post(verifier(api.URL), url.Values{"email": {"[email protected]"}, "_bot403": {"token"}}); code != 303 {
		t.Fatalf("status %d, want 303", code)
	}
	if got.Get("_bot403") != "token" {
		t.Fatalf("the API got %v, want the _bot403 field", got)
	}
}

func TestFailedTokenIsRefused(t *testing.T) {
	var got url.Values
	api := fakeAPI(t, 200, `{"ok":false,"reason":"invalid"}`, &got)
	if code := post(verifier(api.URL), url.Values{"email": {"[email protected]"}}); code != 400 {
		t.Fatalf("status %d, want 400", code)
	}
}

func TestWrongKeyIsAServerError(t *testing.T) {
	var got url.Values
	api := fakeAPI(t, 401, `{"error":"unauthorized"}`, &got)
	if code := post(verifier(api.URL), url.Values{"_bot403": {"token"}}); code != 500 {
		t.Fatalf("status %d, want 500", code)
	}
}

func TestNoAnswerLetsTheFormThrough(t *testing.T) {
	api := httptest.NewServer(http.NotFoundHandler())
	api.Close() // nothing listens here now
	if code := post(verifier(api.URL), url.Values{"_bot403": {"token"}}); code != 303 {
		t.Fatalf("status %d, want 303", code)
	}
}
Terminal
go test ./...
# ok  	contact	0.631s

Then run go run . and open http://localhost:3000/contact. Send the form. The browser goes to /thanks, and the site in your dashboard shows one check. If you get a failure that you do not expect, read the troubleshooting page. It lists every reason and its fix. For a Python server, read Stop form spam in Flask. All guides are in the guides index.

Stop spam, not customers.

The CAPTCHA your visitors never see.

Get started free