A Go Gin microservice in front of the SellerMagnet API validates every request with a regex and a set membership check before it can spend a credit, answers repeat lookups from a mutex-guarded in-process cache, and retries only the status codes a second attempt can fix. This guide builds that wrapper - validate.go, cache.go and server.go are new, and the Go quickstart's own client.go, get.go, lookup.go and retry.go are reused unchanged - and tests all of it with go test -race against a fails-closed fake http.RoundTripper so nothing here is just described.
Key Takeaways
- Validate asin and marketplace_id before the upstream call, so a bad request costs nothing and waits on no timeout.
- A TTLCache needs its own sync.Mutex here, unlike a single-worker-process dict: Gin runs one goroutine per request, so two requests for the same ASIN can race on a plain map.
- The retry policy is the quickstart's own: 429 waits for free, a 500 is retried once (it is refunded), 502/503 are retried up to 4 times (each billed), and a 404 is a real answer, never retried.
- A plain network error (DNS failure, refused connection) is not an *APIError, so withRetry retries it the same way it retries a billed 502/503 - up to the attempt cap - but nothing was ever charged for it.
- client.go, get.go, lookup.go and retry.go do not change between a goroutine-per-request Gin route and the quickstart's own worker-pool script: the same http.Client fits both.
Why wrap the API in a microservice instead of calling it directly?
A thin service in front of the API gives every caller in a larger system one place that enforces the request shape, one cache for ASINs several callers ask for repeatedly, and one retry policy, instead of each caller reimplementing the Go quickstart's client.go, get.go, lookup.go and retry.go on its own. This post reuses those four files unchanged - the package-level httpClient they build is already safe for concurrent use by multiple goroutines, which is exactly how Gin calls a route handler for every request.
Dependencies
go mod init example.com/amazon-gin
go get github.com/gin-gonic/gin@latest
export SELLERMAGNET_API_KEY="your-key-here"
How do I validate the ASIN and marketplace before spending a credit?
Put the shape checks in one function and call it before any network call. An ASIN is always 10 upper-case letters or digits; the marketplace ID must be one this wrapper actually supports (the full list of all 23 marketplace IDs is in the marketplace IDs list). A failing check returns a *ValidationError before the Gin handler ever opens a connection, so a malformed request never waits on the 120-second timeout and never costs a credit. Two fields do not need a validation library: regexp and a map[string]bool are enough, and there is one fewer dependency to pin.
validate.go - checked before any network call
package main
import "regexp"
var asinRe = regexp.MustCompile(`^[A-Z0-9]{10}$`)
// The handful of marketplace IDs this wrapper covers; the full list of all 23
// is in https://sellermagnet-api.com/blog/amazon-marketplace-ids-list
var marketplaceIDs = map[string]bool{
"ATVPDKIKX0DER": true, // amazon.com
"A1PA6795UKMFR9": true, // amazon.de
"A1F83G8C2ARO7P": true, // amazon.co.uk
"A13V1IB3VIYZZH": true, // amazon.fr
}
// ValidationError lists every field that failed, so a client gets one
// response for several bad fields instead of correcting them one at a time.
type ValidationError struct {
Errors []FieldError
}
type FieldError struct {
Field string `json:"field"`
Msg string `json:"msg"`
}
func (e *ValidationError) Error() string { return "invalid lookup request" }
// validateLookupRequest upper-cases the ASIN and checks both fields before any
// network call: a bad shape never opens a connection, so it never spends a
// credit and never waits on the 120 s timeout.
func validateLookupRequest(asinRaw, marketplaceID string) (asin string, mktID string, err error) {
var errs []FieldError
asin = upper(asinRaw)
if !asinRe.MatchString(asin) {
errs = append(errs, FieldError{"asin", "asin must be 10 upper-case letters/digits"})
}
if !marketplaceIDs[marketplaceID] {
errs = append(errs, FieldError{"marketplace_id", "unknown marketplace_id: " + marketplaceID})
}
if len(errs) > 0 {
return "", "", &ValidationError{Errors: errs}
}
return asin, marketplaceID, nil
}
func upper(s string) string {
b := []byte(s)
for i, c := range b {
if c >= 'a' && c <= 'z' {
b[i] = c - 'a' + 'A'
}
}
return string(b)
}
How does the cache stay safe when Gin runs one goroutine per request?
TTLCache is a plain map keyed by asin:marketplaceID, with each entry carrying its own expiry, but it is guarded by its own sync.Mutex. A single-worker-process route only ever touches its process's dict from one request at a time; a Gin server calls the route handler in a new goroutine for every concurrent request, so two lookups for the same ASIN arriving together can race on a bare map without a lock. A lookup within the TTL (300 seconds here) returns the stored result with Cached: true and makes no network call at all; this service also runs as one process, so running several replicas behind a load balancer still means each one keeps its own cache - the same single-process trade-off applies here too, not hidden either.
cache.go - a mutex-guarded in-process TTL cache
package main
import (
"sync"
"time"
)
// TTLCache is a tiny in-process cache, keyed by "asin:marketplaceId". A Gin
// handler runs one goroutine per request on the same process, so - unlike a
// single-worker-process dict - this one needs its own mutex:
// two requests for the same ASIN can race on the same map without it.
type TTLCache struct {
mu sync.Mutex
ttl time.Duration
store map[string]entry
}
type entry struct {
expiresAt time.Time
value lookupResult
}
func newTTLCache(ttl time.Duration) *TTLCache {
return &TTLCache{ttl: ttl, store: make(map[string]entry)}
}
func (c *TTLCache) get(key string) (lookupResult, bool) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.store[key]
if !ok || time.Now().After(e.expiresAt) {
if ok {
delete(c.store, key) // expired: evict so len() reflects live entries only
}
return lookupResult{}, false
}
return e.value, true
}
func (c *TTLCache) set(key string, v lookupResult) {
c.mu.Lock()
defer c.mu.Unlock()
c.store[key] = entry{expiresAt: time.Now().Add(c.ttl), value: v}
}
func (c *TTLCache) len() int {
c.mu.Lock()
defer c.mu.Unlock()
return len(c.store)
}
What does the Gin route itself look like?
The handler validates the path and query parameters first, checks the cache, and only then calls withRetry around the quickstart's own Lookup, which runs through the shared package-level httpClient client.go builds. A plain network error - a dropped connection, not an *APIError - does not stop withRetry early: it is retried up to the same attempt cap as a billed 502/503, the difference being that nothing was ever charged for it.
server.go - the Gin microservice
package main
import (
"context"
"errors"
"net"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// lookupResult is the trimmed shape returned to the caller; Price.Value stays
// nil for "N/A" (no featured offer) so the client never reads that as $0.
type lookupResult struct {
ASIN string `json:"asin"`
Title string `json:"title"`
Price *float64 `json:"price"`
Currency string `json:"currency"`
Cached bool `json:"cached"`
}
// newRouter wires one route: GET /lookup/:asin?marketplace_id=.... Validation
// (validate.go) and the cache (cache.go) are new; client.go, get.go, lookup.go
// and retry.go above are the Go quickstart's own files, unchanged.
func newRouter(cache *TTLCache) *gin.Engine {
r := gin.New()
r.Use(gin.Recovery())
r.GET("/lookup/:asin", func(c *gin.Context) {
asin, marketplaceID, err := validateLookupRequest(c.Param("asin"), c.Query("marketplace_id"))
if err != nil {
var verr *ValidationError
errors.As(err, &verr)
c.JSON(http.StatusBadRequest, gin.H{"detail": verr.Errors}) // bad shape: no network call made
return
}
cacheKey := asin + ":" + marketplaceID
if hit, ok := cache.get(cacheKey); ok {
hit.Cached = true
c.JSON(http.StatusOK, hit)
return
}
var product *Product
callErr := withRetry(c.Request.Context(), 4, func(ctx context.Context) error {
p, err := Lookup(ctx, asin, marketplaceID)
if err != nil {
return err
}
product = p
return nil
})
if callErr != nil {
var apiErr *APIError
if errors.As(callErr, &apiErr) {
if apiErr.Status == http.StatusNotFound {
c.JSON(http.StatusNotFound, gin.H{"detail": "asin not found on this marketplace"})
return
}
c.JSON(http.StatusBadGateway, gin.H{"detail": "upstream lookup failed"})
return
}
// A network error (DNS failure, connection refused) or the 120 s client
// timeout: never reached the server as a billed response, same 502 the
// caller sees for a billed 5xx, but nothing here was ever charged.
var netErr net.Error
_ = errors.As(callErr, &netErr)
c.JSON(http.StatusBadGateway, gin.H{"detail": "upstream unreachable"})
return
}
result := lookupResult{
ASIN: product.ASIN,
Title: product.Title,
Price: product.BuyBoxInfo.Price.Value, // nil stays nil, never coerced to 0
Currency: product.BuyBoxInfo.CurrencyCode,
Cached: false,
}
cache.set(cacheKey, result)
c.JSON(http.StatusOK, result)
})
return r
}
// newServer is a thin wrapper so main.go can set sane HTTP server timeouts;
// not separately tested beyond newRouter, which the test suite drives directly.
func newServer(addr string, cache *TTLCache) *http.Server {
return &http.Server{
Addr: addr,
Handler: newRouter(cache),
ReadTimeout: 10 * time.Second,
WriteTimeout: 130 * time.Second, // above the 120 s upstream timeout plus retries
}
}
A client timeout is not the same as a free connection error
The connection-error branch above only ever fires when the request never reached the server at all (DNS failure, refused connection), so nothing was billed. A client timeout is different: the credit is deducted on the server before the scrape even starts, so a client that gives up waiting and cancels its own context has still paid for an answer it will never see, and that credit is not refunded (refunds only exist for a server-side 500 without Retry-After). Keep the client timeout at 120 seconds, matching the quickstart's own newHTTPClient, rather than cutting it short to "fail fast".

Trimmed response for a cache-miss lookup
{
"asin": "B0CL61F39H",
"title": "PlayStation\u00ae5 console (slim)",
"price": 444.99,
"currency": "USD",
"cached": false
}
| Scenario | HTTP status | Retried? | Billed? |
|---|---|---|---|
| Valid ASIN, cache miss | 200 | - | Yes (1 credit) |
| Same lookup again within 300s | 200 (cached) | no | No - 0 upstream calls |
| Malformed ASIN shape | 400 | no | No - rejected before the network |
| Unknown marketplace_id | 400 | no | No - rejected before the network |
| Lower-case ASIN, cache miss | 200 | - | Yes - normalized then looked up |
| Upstream 404 (not on this marketplace) | 404 | no | Yes - a real answer |
| Upstream 429 (concurrency cap) | 200 (after a wait) | yes - free | No - the 429 itself |
| Upstream 500 (refunded) | 200 (after 1 retry) | yes, capped at 1 | No - the 500 itself |
| Two upstream 500s in a row | 502 | no - stops | No - the 500s |
| Upstream 502 / 503 | 502 | yes, up to 4 attempts | Yes - every attempt |
| Connection error (never reached the server) | 502 | yes, up to 4 attempts | No - nothing was billed |

server_test.go - 14 scenarios against a fails-closed fake http.RoundTripper, run with -race
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/gin-gonic/gin"
)
const (
testASIN = "B0CL61F39H"
testMP = "ATVPDKIKX0DER"
)
func product(price any) map[string]any {
return map[string]any{
"asin": testASIN,
"title": "PlayStation5 console (slim)",
"link": "https://www.amazon.com/dp/" + testASIN,
"buyBoxInfo": map[string]any{
"price": price,
"currencyCode": "USD",
"sellerId": "Amazon",
},
}
}
// newTestRouter gives every test its own cache and engine, and resets the
// fake transport's route - a forgotten reset must not leak between tests.
func newTestRouter(t *testing.T) *gin.Engine {
t.Cleanup(func() { reset(); wantConnErr = false })
return newRouter(newTTLCache(300 * time.Second))
}
func doLookup(r *gin.Engine, asin, marketplaceID string) *httptest.ResponseRecorder {
req := httptest.NewRequest("GET", "/lookup/"+asin+"?marketplace_id="+marketplaceID, nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestValidLookupReturnsPriceAndIsNotCached(t *testing.T) {
r := newTestRouter(t)
install(func(ep string, p url.Values) (int, any, http.Header) {
return ok(map[string]any{"productInfo": product(444.99)})
})
w := doLookup(r, testASIN, testMP)
if w.Code != 200 {
t.Fatalf("status = %d, want 200", w.Code)
}
var got lookupResult
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if got.Cached || got.Price == nil || *got.Price != 444.99 || got.Currency != "USD" {
t.Fatalf("unexpected body: %+v", got)
}
if callCount() != 1 {
t.Fatalf("calls = %d, want 1", callCount())
}
}
func TestSecondLookupIsServedFromCacheWithoutASecondCall(t *testing.T) {
r := newTestRouter(t)
install(func(ep string, p url.Values) (int, any, http.Header) {
return ok(map[string]any{"productInfo": product(444.99)})
})
first := doLookup(r, testASIN, testMP)
second := doLookup(r, testASIN, testMP)
var firstBody, secondBody lookupResult
json.Unmarshal(first.Body.Bytes(), &firstBody)
json.Unmarshal(second.Body.Bytes(), &secondBody)
if firstBody.Cached {
t.Fatal("first lookup should not be cached")
}
if !secondBody.Cached {
t.Fatal("second lookup should be served from cache")
}
if callCount() != 1 {
t.Fatalf("calls = %d, want 1 (only the first lookup should reach the upstream)", callCount())
}
}
func TestMalformedASINIsRejectedBefore400AndNoNetworkCall(t *testing.T) {
r := newTestRouter(t)
w := doLookup(r, "short", testMP)
if w.Code != 400 {
t.Fatalf("status = %d, want 400", w.Code)
}
if callCount() != 0 {
t.Fatalf("calls = %d, want 0 (malformed ASIN never reaches the network)", callCount())
}
}
func TestUnknownMarketplaceIsRejectedBefore400AndNoNetworkCall(t *testing.T) {
r := newTestRouter(t)
w := doLookup(r, testASIN, "A2Q3Y263D00KWC")
if w.Code != 400 {
t.Fatalf("status = %d, want 400", w.Code)
}
if callCount() != 0 {
t.Fatalf("calls = %d, want 0", callCount())
}
}
func TestLowerCaseASINIsNormalizedThenLookedUp(t *testing.T) {
r := newTestRouter(t)
install(func(ep string, p url.Values) (int, any, http.Header) {
if p.Get("asin") != testASIN {
t.Fatalf("upstream saw asin=%q, want upper-cased %q", p.Get("asin"), testASIN)
}
return ok(map[string]any{"productInfo": product(19.99)})
})
w := doLookup(r, "b0cl61f39h", testMP)
if w.Code != 200 {
t.Fatalf("status = %d, want 200", w.Code)
}
}
func TestUpstream404IsBilledAndNeverRetried(t *testing.T) {
r := newTestRouter(t)
install(func(ep string, p url.Values) (int, any, http.Header) {
return fail(404, "Product not found.", nil)
})
w := doLookup(r, testASIN, testMP)
if w.Code != 404 {
t.Fatalf("status = %d, want 404", w.Code)
}
if callCount() != 1 {
t.Fatalf("calls = %d, want 1 (a 404 is a real answer, never retried)", callCount())
}
}
func TestUpstream429IsFreeAndRetriedUntilItSucceeds(t *testing.T) {
r := newTestRouter(t)
first := true
install(func(ep string, p url.Values) (int, any, http.Header) {
if first {
first = false
h := http.Header{}
h.Set("Retry-After", "1")
return fail(429, "concurrency cap", h)
}
return ok(map[string]any{"productInfo": product(444.99)})
})
w := doLookup(r, testASIN, testMP)
if w.Code != 200 {
t.Fatalf("status = %d, want 200 after the 429 clears", w.Code)
}
if callCount() != 2 {
t.Fatalf("calls = %d, want 2 (the 429 itself cost nothing)", callCount())
}
}
func TestUpstream500IsRefundedAndRetriedExactlyOnce(t *testing.T) {
r := newTestRouter(t)
first := true
install(func(ep string, p url.Values) (int, any, http.Header) {
if first {
first = false
return fail(500, "internal error", nil)
}
return ok(map[string]any{"productInfo": product(29.99)})
})
w := doLookup(r, testASIN, testMP)
if w.Code != 200 {
t.Fatalf("status = %d, want 200 after one retry", w.Code)
}
if callCount() != 2 {
t.Fatalf("calls = %d, want 2", callCount())
}
}
func TestTwoConsecutive500sStopInsteadOfLoopingForever(t *testing.T) {
r := newTestRouter(t)
install(func(ep string, p url.Values) (int, any, http.Header) {
return fail(500, "internal error", nil)
})
w := doLookup(r, testASIN, testMP)
if w.Code != 502 {
t.Fatalf("status = %d, want 502 (wrapper's own gateway error for an upstream failure)", w.Code)
}
if callCount() != 2 {
t.Fatalf("calls = %d, want 2 (refund-once means the second 500 is never retried a 3rd time)", callCount())
}
}
func TestUpstream502IsBilledOnEveryAttemptUpToTheCap(t *testing.T) {
r := newTestRouter(t)
n := 0
install(func(ep string, p url.Values) (int, any, http.Header) {
n++
if n < 3 {
return fail(502, "bad gateway", nil)
}
return ok(map[string]any{"productInfo": product(39.99)})
})
w := doLookup(r, testASIN, testMP)
if w.Code != 200 {
t.Fatalf("status = %d, want 200 (succeeds on the 3rd attempt)", w.Code)
}
if callCount() != 3 {
t.Fatalf("calls = %d, want 3, each billed", callCount())
}
}
func TestUpstream503StaysCappedAtFourAttemptsNeverAFifth(t *testing.T) {
r := newTestRouter(t)
install(func(ep string, p url.Values) (int, any, http.Header) {
return fail(503, "service unavailable", nil)
})
w := doLookup(r, testASIN, testMP)
if w.Code != 502 {
t.Fatalf("status = %d, want 502", w.Code)
}
if callCount() != 4 {
t.Fatalf("calls = %d, want 4 (capped), never a 5th", callCount())
}
}
func TestConnectionErrorIsNeverBilledAndSurfacesAs502(t *testing.T) {
r := newTestRouter(t)
installConnErr()
w := doLookup(r, testASIN, testMP)
if w.Code != 502 {
t.Fatalf("status = %d, want 502", w.Code)
}
}
func TestFakeTransportFailsClosedWithoutInstall(t *testing.T) {
r := newTestRouter(t)
// gin.Recovery() catches the fake transport's panic and turns it into a
// 500, instead of a request silently reaching the real API - this is
// the fail-closed guarantee under test, observed through the response.
w := doLookup(r, testASIN, testMP)
if w.Code != 500 {
t.Fatalf("status = %d, want 500 (no route installed, the fake must panic, not pass a request through)", w.Code)
}
}
func TestConcurrentLookupsOfTheSameASINShareOneCacheSafely(t *testing.T) {
r := newTestRouter(t)
install(func(ep string, p url.Values) (int, any, http.Header) {
return ok(map[string]any{"productInfo": product(444.99)})
})
// Fires 20 concurrent requests for the same key at the TTLCache; with go
// test -race this proves cache.go's mutex, not just that it compiles.
done := make(chan int, 20)
for i := 0; i < 20; i++ {
go func() {
w := doLookup(r, testASIN, testMP)
done <- w.Code
}()
}
for i := 0; i < 20; i++ {
if code := <-done; code != 200 {
t.Fatalf("concurrent lookup returned %d, want 200", code)
}
}
}
Real output: go test -race -v ./... (unmodified run)
=== RUN TestValidLookupReturnsPriceAndIsNotCached
--- PASS: TestValidLookupReturnsPriceAndIsNotCached (0.00s)
=== RUN TestSecondLookupIsServedFromCacheWithoutASecondCall
--- PASS: TestSecondLookupIsServedFromCacheWithoutASecondCall (0.00s)
=== RUN TestMalformedASINIsRejectedBefore400AndNoNetworkCall
--- PASS: TestMalformedASINIsRejectedBefore400AndNoNetworkCall (0.00s)
=== RUN TestUnknownMarketplaceIsRejectedBefore400AndNoNetworkCall
--- PASS: TestUnknownMarketplaceIsRejectedBefore400AndNoNetworkCall (0.00s)
=== RUN TestLowerCaseASINIsNormalizedThenLookedUp
--- PASS: TestLowerCaseASINIsNormalizedThenLookedUp (0.00s)
=== RUN TestUpstream404IsBilledAndNeverRetried
--- PASS: TestUpstream404IsBilledAndNeverRetried (0.00s)
=== RUN TestUpstream429IsFreeAndRetriedUntilItSucceeds
--- PASS: TestUpstream429IsFreeAndRetriedUntilItSucceeds (2.54s)
=== RUN TestUpstream500IsRefundedAndRetriedExactlyOnce
--- PASS: TestUpstream500IsRefundedAndRetriedExactlyOnce (2.88s)
=== RUN TestTwoConsecutive500sStopInsteadOfLoopingForever
--- PASS: TestTwoConsecutive500sStopInsteadOfLoopingForever (2.22s)
=== RUN TestUpstream502IsBilledOnEveryAttemptUpToTheCap
--- PASS: TestUpstream502IsBilledOnEveryAttemptUpToTheCap (7.34s)
=== RUN TestUpstream503StaysCappedAtFourAttemptsNeverAFifth
--- PASS: TestUpstream503StaysCappedAtFourAttemptsNeverAFifth (15.61s)
=== RUN TestConnectionErrorIsNeverBilledAndSurfacesAs502
--- PASS: TestConnectionErrorIsNeverBilledAndSurfacesAs502 (16.21s)
=== RUN TestFakeTransportFailsClosedWithoutInstall
--- PASS: TestFakeTransportFailsClosedWithoutInstall (0.03s)
=== RUN TestConcurrentLookupsOfTheSameASINShareOneCacheSafely
--- PASS: TestConcurrentLookupsOfTheSameASINShareOneCacheSafely (0.02s)
PASS
ok example.com/amazon-gin 47.997s
This cache is per process, and so is the test suite's fake transport
Running the service as several replicas behind a load balancer means each one holds its own cache, so the same ASIN can still be fetched once per replica within the TTL. That is a reasonable default for a single small service; a reader running several replicas should size the TTL around that, or swap in a shared store of their own choice - this post does not name one.
Frequently Asked Questions
Why validate with regexp and a map instead of a struct-tag validator library?
Either works. For two fields - an ASIN regex and a marketplace set membership check - a small function avoids an extra dependency; a larger request shape is a better fit for a tag-based validator.
Does the cache in this wrapper work across multiple replicas?
No. TTLCache is a plain in-process map guarded by its own mutex; each replica keeps its own copy. Several replicas sharing one cache need an external store, which is outside this post's scope.
Which status codes does the wrapper retry?
429 is waited out for free, a 500 is retried once since it is refunded, and 502/503 are retried up to 4 attempts total since each is billed. A 404 is never retried.
Why does a connection error still get retried up to the attempt cap?
withRetry retries any error it sees unless it can prove (via APIError) that retrying is pointless; a plain network error is not an APIError, so it gets the same attempt cap as a billed 502/503 - the difference is that a connection error was never charged.
Why does the cache need a sync.Mutex here but not in a single-worker synchronous service?
A single synchronous worker process only ever runs one request at a time against its own cache dict. Gin calls the handler in a new goroutine per request, so concurrent requests for the same key can race on a bare map without a lock.
Bottom line: validate before any network call, cache repeat lookups for free in a mutex-guarded in-process TTLCache, and reuse the quickstart's own client and retry policy unchanged. Every behaviour here came from running go test -race against real code with only http.RoundTripper faked - see the Go quickstart for the client's own retry details and the API documentation for every endpoint.