# How to A/B test prices in Go

Source: https://leverprice.com/guides/go
Updated: 2026-11-17

> Add the leverprice-go module, create one client at startup and preload it, then in the handler that renders the price call GetPrice(r.Context(), ...) and q.WriteCookies(w) before writing the body. At checkout, price again and pass q.Price and the whole q.Metadata to a stripe-go Checkout Session. Shut down with srv.Shutdown and lp.Close so queued exposures are sent.

In Go, a price test is two handlers and a shutdown path. The handlers are short. The shutdown path is where data goes missing: `log.Fatal(http.ListenAndServe(...))` exits through `os.Exit`, which skips the deferred `Close` that would have sent the last exposures.

The code below uses net/http with [Go 1.22 routing patterns](https://go.dev/blog/routing-enhancements), stripe-go v87 and `github.com/leverprice/leverprice-go`, which needs Go 1.22 or newer and nothing outside the standard library.

## How does price testing work in a Go service?

Your server decides the price. `GetPrice` reads the visitor's `__pp` cookie and user agent from the `*http.Request`, picks their price from a signed config held in memory, checks it against bounds you set in code and returns a `*Quote`: `Price` in minor units (2900 is $29.00), `Currency`, signed `Metadata` and a slice of Set-Cookie values. No Leverprice JavaScript runs in the browser.

*Figure: Diagram: a visitor requests the pricing page, your server asks the SDK for a price, the checkout charges that price, and Leverprice moves traffic toward the best earner. Your handlers ask for the price twice: once to render it and once to charge it.*

The checkout handler calls `GetPrice` again and gets the same answer, because the signed cookie comes back with the browser. Stripe later confirms the payment to Leverprice with a signed webhook. The case for doing all of this on the server is in [server-side price testing](https://leverprice.com/blog/server-side-price-testing).

## How do I set up the client in Go?

```bash
go get github.com/leverprice/leverprice-go github.com/stripe/stripe-go/v87
```

Set `LEVERPRICE_SECRET_KEY` (`pp_sk_test_…` locally), `STRIPE_SECRET_KEY` and `APP_URL` in the environment. Create one client for the whole process, preload it with a deadline, and shut down in an order that lets queued events go out:

```go title="main.go"
package main

import (
	"context"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/leverprice/leverprice-go"
	"github.com/stripe/stripe-go/v87"
)

var (
	lp *leverprice.Client
	sc *stripe.Client
)

func main() {
	var err error
	lp, err = leverprice.New(leverprice.Options{
		SecretKey: os.Getenv("LEVERPRICE_SECRET_KEY"),
		Products: map[string]leverprice.ProductGuard{
			// Guardrails in minor units: a price outside them is never returned.
			"pro": {Currency: "usd", FallbackPrice: 2900, MinPrice: 1900, MaxPrice: 4900},
		},
	})
	if err != nil {
		log.Fatal(err) // invalid Options only
	}
	sc = stripe.NewClient(os.Getenv("STRIPE_SECRET_KEY"))

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	preloadCtx, cancelPreload := context.WithTimeout(ctx, 2*time.Second)
	lp.Preload(preloadCtx)
	cancelPreload()

	mux := http.NewServeMux()
	mux.HandleFunc("GET /pricing", pricing)
	mux.HandleFunc("POST /checkout", checkout)
	mux.HandleFunc("POST /webhooks/stripe", stripeWebhook)

	srv := &http.Server{Addr: ":8080", Handler: http.NewCrossOriginProtection().Handler(mux)}
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()

	<-ctx.Done()
	shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancelShutdown()
	_ = srv.Shutdown(shutdownCtx) // stop accepting, finish in-flight requests
	lp.Close(shutdownCtx)         // then send queued exposures
}
```

`leverprice.New` fails only for invalid options. Everything else fails safe: with no key, `LEVERPRICE_DISABLED=1`, or no signed config within `Timeout` (500 ms by default), `GetPrice` returns your `FallbackPrice`, and its only error is a product key missing from `Products`. The [SDK docs](https://leverprice.com/docs) list every option.

The order at the bottom matters. The [os.Exit docs](https://pkg.go.dev/os#Exit) say "deferred functions are not run", and `log.Fatal` calls it, so a `defer lp.Close(...)` next to a fatal `ListenAndServe` never fires. `Shutdown` makes `ListenAndServe` return `ErrServerClosed` and waits for active requests; `Close` then flushes.

`http.NewCrossOriginProtection` (Go 1.25+) rejects cross-origin browser POSTs to `/checkout`, while Stripe's server-to-server webhook, which sends neither `Sec-Fetch-Site` nor `Origin`, passes, per the [net/http docs](https://pkg.go.dev/net/http#CrossOriginProtection). On Go 1.22 to 1.24, drop that wrapper.

## How do I show the tested price in a handler?

```go title="pricing.go"
package main

import (
	"fmt"
	"html/template"
	"net/http"
	"strings"

	"github.com/leverprice/leverprice-go"
)

var page = template.Must(template.New("pricing").Parse(
	`<p class="price">{{.Amount}} {{.Currency}}</p>
<form method="post" action="/checkout"><button type="submit">Buy Pro</button></form>`))

func pricing(w http.ResponseWriter, r *http.Request) {
	q, err := lp.GetPrice(r.Context(), "pro", leverprice.PriceRequest{Request: r, UserID: userID(r)})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError) // unknown product key
		return
	}
	q.WriteCookies(w) // before the first byte of the body
	page.Execute(w, map[string]string{
		"Amount":   fmt.Sprintf("%d.%02d", q.Price/100, q.Price%100),
		"Currency": strings.ToUpper(q.Currency),
	})
}

// userID returns the signed-in user's id, or "" for anonymous visitors.
func userID(r *http.Request) string { return "" }
```

Call `WriteCookies` before anything writes the body. The [ResponseWriter docs](https://pkg.go.dev/net/http#ResponseWriter) say changing the header map after `WriteHeader` or `Write` "has no effect", so a cookie added after `page.Execute` vanishes without an error, and every reload can land on a new price.

`UserID` puts a signed-in customer in the same bucket on every device, and only an HMAC of it leaves your server. It is a string, so convert numeric ids with `strconv.FormatInt`.

## How do context deadlines affect GetPrice?

They can only shorten the wait. While no config is loaded yet, `GetPrice` waits at most `Timeout` after the fetch started, or until `ctx` is done, whichever comes first, then returns your fallback price. The fetch itself runs in its own goroutine and keeps going, so the next request picks up the config.

A server-wide deadline below 500 ms, from `http.TimeoutHandler` or a middleware's `context.WithTimeout`, makes cold-start requests give up sooner. Those visitors get the fallback with reason `no_config` and a 30-minute pin cookie, so their price stays put rather than flipping mid-session. That is why `main` preloads before it starts listening: the first visitors after a deploy then get real prices. Pass `r.Context()` every time; with a loaded config, `GetPrice` doesn't wait at all.

## How do I charge the same price with Stripe Checkout?

Price the checkout on the server again and ignore any amount the form sends. stripe-go's `CheckoutSessionCreateParams` take the amount inline through `PriceData`, so there is no Stripe Price per tested price:

```go title="checkout.go"
package main

import (
	"net/http"
	"os"

	"github.com/leverprice/leverprice-go"
	"github.com/stripe/stripe-go/v87"
)

var appURL = os.Getenv("APP_URL") // e.g. https://example.com

func checkout(w http.ResponseWriter, r *http.Request) {
	q, err := lp.GetPrice(r.Context(), "pro", leverprice.PriceRequest{Request: r, UserID: userID(r)})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	q.WriteCookies(w)
	params := &stripe.CheckoutSessionCreateParams{
		Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
		LineItems: []*stripe.CheckoutSessionCreateLineItemParams{{
			Quantity: stripe.Int64(1),
			PriceData: &stripe.CheckoutSessionCreateLineItemPriceDataParams{
				Currency:    stripe.String(q.Currency),
				UnitAmount:  stripe.Int64(q.Price),
				ProductData: &stripe.CheckoutSessionCreateLineItemPriceDataProductDataParams{Name: stripe.String("Pro")},
			},
		}},
		Metadata:          q.Metadata, // signed attribution: pass it whole
		PaymentIntentData: &stripe.CheckoutSessionCreatePaymentIntentDataParams{Metadata: q.Metadata},
		SuccessURL:        stripe.String(appURL + "/thanks"),
		CancelURL:         stripe.String(appURL + "/pricing"),
	}
	s, err := sc.V1CheckoutSessions.Create(r.Context(), params)
	if err != nil {
		http.Error(w, "checkout unavailable", http.StatusBadGateway)
		return
	}
	http.Redirect(w, r, s.URL, http.StatusSeeOther)
}
```

These are the stripe-go v87 names: `stripe.NewClient`, `sc.V1CheckoutSessions.Create` and the `CheckoutSessionCreate…Params` types, as in the [Checkout Session API reference](https://docs.stripe.com/api/checkout/sessions/create). `q.Price` is an `int64` in minor units and `q.Metadata` a `map[string]string`, so both drop in without conversion. The metadata holds `pp_exp`, `pp_var`, `pp_vid` and `pp_sig`, signed together, so it goes into Stripe whole.

Selling a subscription? Use `stripe.CheckoutSessionModeSubscription`, add `Recurring` to `PriceData`, and move the metadata copy to `SubscriptionData`, since Stripe accepts `payment_intent_data` only in payment mode. Leverprice's Stripe verification covers one-time payments, so a subscription's first payment has to be reported with `TrackPurchase` from your own webhook handler, below; it shows as unverified, and renewals never count toward a test.

Other providers follow the same two rules: charge `q.Price`, pass `q.Metadata` whole. [Polar](https://leverprice.com/integrations/polar) accepts an ad-hoc price per checkout, and Leverprice verifies one-time orders and a subscription's first payment there. [Lemon Squeezy](https://leverprice.com/integrations/lemon-squeezy) takes `custom_price` in cents but [stops processing payments on March 31, 2027](https://www.lemonsqueezy.com/blog/saying-goodbye-to-lemon-squeezy). [Dodo Payments](https://leverprice.com/integrations/dodo-payments) takes a custom amount only on pay-what-you-want products, with one-time payments verified.

## Can I show a different price per country?

Yes. With regional prices on in the dashboard, each country gets a price you set by hand or one derived from its tier (5 tiers by World Bank price level), in its own currency. Example: ₹999 for a visitor in India, $29 in the US. Your options decide where the country comes from and which prices may pass:

```go title="main.go"
lp, err = leverprice.New(leverprice.Options{
	SecretKey:     os.Getenv("LEVERPRICE_SECRET_KEY"),
	CountryHeader: "CF-IPCountry", // set by Cloudflare; CloudFront: CloudFront-Viewer-Country
	Products: map[string]leverprice.ProductGuard{
		"pro": {
			Currency: "usd", FallbackPrice: 2900, MinPrice: 1900, MaxPrice: 4900,
			Regional: map[string]leverprice.RegionalBounds{ // currencies you accept, each with hard bounds
				"usd": {MinPrice: 800, MaxPrice: 4900},
				"eur": {MinPrice: 1100, MaxPrice: 6000},
				"inr": {MinPrice: 48000, MaxPrice: 230000},
			},
		},
	},
})
```

`CountryHeader` has no default on purpose: a header visitors can send themselves would let them pick their price, and it is only safe if every request reaches your binary through the CDN that overwrites it. If you look the country up yourself, set `Country` in `PriceRequest`; it wins over the header. Unlisted currencies, prices outside their bounds, bots and unknown countries get the standard price.

The checkout already passes `q.Currency`, so Stripe charges in the visitor's currency; confirm your account supports each one. The `%d.%02d` formatting above fits two-decimal currencies only. JPY has no minor unit, per Stripe's [zero-decimal list](https://docs.stripe.com/currencies#zero-decimal).

## How does Leverprice verify revenue from Stripe?

Stripe sends signed webhooks to Leverprice directly. In the dashboard, open Payments and connect Stripe to get an endpoint URL. Add it in Stripe for `checkout.session.completed`, `checkout.session.async_payment_succeeded` and `charge.refunded`, then paste that endpoint's signing secret into Leverprice.

A signing secret can confirm events but cannot move money, so an API key never goes there. The [Stripe integration page](https://leverprice.com/integrations/stripe) has the details, and [verified revenue](https://leverprice.com/blog/verified-revenue-webhooks) covers why the signature matters. Write your own handler only if you cannot add an endpoint or you sell subscriptions; what it reports is labeled unverified and never overrides a verified purchase:

```go title="webhook.go"
package main

import (
	"encoding/json"
	"io"
	"net/http"
	"os"

	"github.com/leverprice/leverprice-go"
	"github.com/stripe/stripe-go/v87"
)

func stripeWebhook(w http.ResponseWriter, r *http.Request) {
	payload, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 65536))
	if err != nil {
		http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
		return
	}
	event, err := sc.ConstructEvent(payload, r.Header.Get("Stripe-Signature"), os.Getenv("STRIPE_WEBHOOK_SECRET"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if event.Type != stripe.EventTypeCheckoutSessionCompleted &&
		event.Type != stripe.EventTypeCheckoutSessionAsyncPaymentSucceeded {
		w.WriteHeader(http.StatusOK)
		return
	}
	var s stripe.CheckoutSession
	if err := json.Unmarshal(event.Data.Raw, &s); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if s.PaymentStatus == stripe.CheckoutSessionPaymentStatusPaid {
		orderID := ""
		if s.PaymentIntent != nil {
			orderID = s.PaymentIntent.ID
		} else if s.Invoice != nil {
			orderID = s.Invoice.ID // subscription mode
		}
		var tax int64
		if s.TotalDetails != nil {
			tax = s.TotalDetails.AmountTax
		}
		lp.TrackPurchase(r.Context(), leverprice.Purchase{
			Provider:  leverprice.ProviderStripe,
			OrderID:   orderID,
			Amount:    s.AmountTotal - tax,
			Currency:  string(s.Currency),
			Metadata:  s.Metadata,
			Timestamp: event.Created, // Unix seconds are converted
		})
	}
	w.WriteHeader(http.StatusOK)
}
```

Two Go-specific notes. `TrackPurchase` waits only until `ctx` is done, and the send continues in the background with retries, so `r.Context()` is fine. And `sc.ConstructEvent` returns an error when the event's API version doesn't match the one stripe-go was built for ([Client.ConstructEvent](https://pkg.go.dev/github.com/stripe/stripe-go/v87#Client.ConstructEvent)); create your endpoint with that version, or pass `stripe.WithIgnoreAPIVersionMismatch()` and accept the decoding risk.

## How do I test it locally?

Run `go run .` with test keys, connect a test-mode Stripe endpoint in Leverprice, and open http://localhost:8080/pricing:

1. Note the price and reload. It must not change.
2. Click Buy and compare Stripe's amount with the page. Pay with a card from Stripe's [testing docs](https://docs.stripe.com/testing), such as 4242 4242 4242 4242.
3. Restart without `LEVERPRICE_SECRET_KEY`: the fallback price appears with reason `disabled`.

curl and Go's own HTTP client get the standard price with reason `bot`, because command-line and library clients count as bots; `httptest` requests carry no user agent and count as people. In unit tests, `t.Setenv("LEVERPRICE_DISABLED", "1")` keeps handlers offline, since the variable is read on every call. `CookieSecure` is a `*bool`, so on a plain-HTTP LAN address pass a pointer to `false` in development; [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie) documents the HTTPS exception only for localhost.

## What changes in production?

Swap in `pp_sk_live_…` and your live Stripe key, point `APP_URL` at the public https address, and connect the live-mode Stripe endpoint in Leverprice with its own signing secret. Kubernetes [sends SIGTERM](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-termination) to the main process before it kills a container, which is exactly what `signal.NotifyContext` in `main` waits for; keep the grace period longer than the 10-second shutdown budget. Probes such as `kube-probe` count as bots, so health checks hitting the pricing page get the standard price and never join the test.

If outbound traffic goes through a proxy, pass your own `*http.Client` as `Options.HTTPClient`. To switch the test off, set `LEVERPRICE_DISABLED=1` and restart: every visitor gets your fallback price with no calls to Leverprice. Python teams get the same startup and shutdown pattern from the lifespan handler in the [FastAPI guide](https://leverprice.com/guides/fastapi).

## Does it work with Gin, Echo or Chi?

Yes. Chi routes plain `http.HandlerFunc`s, so the handlers above work unchanged. In Gin and Echo, pass the underlying request and write the cookies to the framework's writer before rendering:

```go title="gin.go"
router.GET("/pricing", func(c *gin.Context) {
	q, err := lp.GetPrice(c.Request.Context(), "pro", leverprice.PriceRequest{Request: c.Request})
	if err != nil {
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	q.WriteCookies(c.Writer) // Echo: q.WriteCookies(c.Response())
	c.JSON(http.StatusOK, gin.H{"price": q.Price, "currency": q.Currency})
})
```

For any other framework, pass the request's `http.Header` as `PriceRequest.Header` and add every `q.SetCookie` value as a Set-Cookie header.

## What breaks most often?

| Symptom | Likely cause | Fix |
|---|---|---|
| Price changes on reload | `WriteCookies` called after the body was written | Call it right after `GetPrice` |
| Exposures missing after each deploy | `log.Fatal` or `os.Exit` skipped the deferred `Close` | `srv.Shutdown`, then `lp.Close` |
| Fallback price for the first visitors after a deploy | Cold start under a request deadline below 500 ms | `Preload` before listening |
| Your webhook rejects every event | stripe-go API version mismatch | Match the endpoint's API version |
| `reason` is `bot` in manual tests | curl or Go's HTTP client user agent | Test in a browser |
| `GetPrice` returns an error | Product key missing from `Products` | Add the key to the options |

## Frequently asked questions

### How do I price monthly and yearly plans in one handler?

Call `GetPrice` once per product key with the same `*http.Request`. The quotes share one visitor until the request's context is done, and the last quote's cookie carries every assignment, so write the cookies of each.

### Does it work on AWS Lambda or other serverless runtimes?

Yes. Create the client outside the handler so warm invocations reuse it, and call `lp.Flush(ctx)` before the handler returns, so exposures don't wait for a timer that may never fire between invocations.

### What happens when the test ends?

You lock in the winner in the dashboard, and every visitor gets it within about a second. The Go code doesn't change and nothing needs a deploy.
