Clavem

How to validate a license key in a Go app

POST the key and the saved instance id to /v1/licenses/validate with a net/http client that has a timeout, decode the reply into a struct, and branch on the status and the valid field. Store the key with go-keyring and retry a 503 once.

This page covers the online validate call in Go. The token check for the offline path is in offline verification in Go, and the first-run call is in device activation in Go. It uses the standard library and documented behavior, and the API behavior it relies on was checked against the live service.

The client

Go’s http.Client returns a response for every HTTP status, so a 404 is not an error. That makes the mapping short. Typed structs also help: a JSON null decodes into a string field as the empty string, and a pointer field tells you whether valid was present at all:

package license

import (
	"bytes"
	"context"
	"encoding/json"
	"io"
	"net/http"
	"strconv"
	"time"
)

const Base = "https://clavem.io"

type Kind int

const (
	Valid    Kind = iota
	NotValid      // 200 with valid: false: expired or disabled
	Unknown       // 404: unknown key, or this device's activation is gone
	NoAnswer      // offline, timeout, 429, 5xx or an unreadable reply
)

type Outcome struct {
	Kind       Kind
	Token      string
	Reason     string
	RetryAfter time.Duration // zero when the server gave no hint
}

type Client struct {
	Base string
	HTTP *http.Client
}

func NewClient() *Client {
	return &Client{Base: Base, HTTP: &http.Client{Timeout: 8 * time.Second}}
}

// post returns an error only when there was no HTTP answer at all.
func (c *Client) post(ctx context.Context, action string, body map[string]string) (status int, raw []byte, retry time.Duration, err error) {
	payload, _ := json.Marshal(body)
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.Base+"/v1/licenses/"+action, bytes.NewReader(payload))
	if err != nil {
		return 0, nil, 0, err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("User-Agent", "Inkwell/3.2")
	res, err := c.HTTP.Do(req)
	if err != nil {
		return 0, nil, 0, err
	}
	defer res.Body.Close()
	raw, err = io.ReadAll(io.LimitReader(res.Body, 1<<20))
	if secs, convErr := strconv.Atoi(res.Header.Get("Retry-After")); convErr == nil {
		retry = time.Duration(secs) * time.Second
	}
	return res.StatusCode, raw, retry, err
}

func (c *Client) Validate(ctx context.Context, key, instanceID string) Outcome {
	body := map[string]string{"license_key": key}
	if instanceID != "" {
		body["instance_id"] = instanceID
	}
	status, raw, retry, err := c.post(ctx, "validate", body)
	if err != nil {
		return Outcome{Kind: NoAnswer}
	}
	var v struct {
		Valid *bool  `json:"valid"`
		Error string `json:"error"` // null decodes as ""
		Token string `json:"token"`
	}
	_ = json.Unmarshal(raw, &v)

	switch status {
	case http.StatusOK:
		switch {
		case v.Valid == nil:
			return Outcome{Kind: NoAnswer}
		case *v.Valid:
			return Outcome{Kind: Valid, Token: v.Token}
		default:
			return Outcome{Kind: NotValid, Token: v.Token, Reason: v.Error}
		}
	case http.StatusNotFound:
		return Outcome{Kind: Unknown, Reason: v.Error}
	case http.StatusTooManyRequests, http.StatusServiceUnavailable:
		return Outcome{Kind: NoAnswer, RetryAfter: retry}
	}
	return Outcome{Kind: NoAnswer} // 400 is a bug in the app; other 5xx is on the server
}

The client’s Timeout covers connecting, redirects and reading the body, which is right for a 2 KB reply. The same field would cut off a large download, which is why software updates in Go does not use it.

What each answer means

Reply Kind What the app does
200, valid: true Valid Store the new token. This restarts the 14-day window.
200, valid: false NotValid Expired or disabled. Store the token, show Reason, keep the key.
404 Unknown Unknown key, or instance_id not found. Clear the license, ask for the key.
429, 503 NoAnswer No verdict. Use the stored token. RetryAfter is 60 or 5 seconds.
Network error NoAnswer Same.

For the two short waits, retry the 503 once and give up on the 429. A context keeps the wait cancellable:

func (c *Client) ValidateWithRetry(ctx context.Context, key, instanceID string) Outcome {
	out := c.Validate(ctx, key, instanceID)
	if out.Kind == NoAnswer && out.RetryAfter > 0 && out.RetryAfter <= 5*time.Second {
		select {
		case <-time.After(out.RetryAfter):
			out = c.Validate(ctx, key, instanceID)
		case <-ctx.Done():
		}
	}
	return out
}

Run it in a goroutine at startup and send the result on a channel, so the program is usable while the request is in flight. A live 400 shows what a malformed call gets: an empty body returns {"valid":false,"error":"license_key: Invalid input: expected string, received undefined"}. That is a bug in your code, not something to show a customer.

Keep the key in the keyring

go-keyring needs no cgo, so it works in a statically linked binary. Its README says macOS goes through the /usr/bin/security binary and Linux through the Secret Service over D-Bus, provided by GNOME Keyring:

package license

import (
	"encoding/json"
	"errors"

	"github.com/zalando/go-keyring"
)

const service = "com.example.inkwell"

type Saved struct {
	Key        string `json:"key"`
	InstanceID string `json:"instance_id"`
	Token      string `json:"token"`
}

func Load() (*Saved, error) {
	s, err := keyring.Get(service, "license")
	if errors.Is(err, keyring.ErrNotFound) {
		return nil, nil // nothing saved yet
	}
	if err != nil {
		return nil, err // no keyring available, or it is locked
	}
	var v Saved
	if err := json.Unmarshal([]byte(s), &v); err != nil {
		return nil, err
	}
	return &v, nil
}

func Save(v Saved) error {
	b, _ := json.Marshal(v)
	return keyring.Set(service, "license", string(b))
}

func Clear() error {
	if err := keyring.Delete(service, "license"); err != nil && !errors.Is(err, keyring.ErrNotFound) {
		return err
	}
	return nil
}

A headless Linux machine usually has no Secret Service, and Load and Save then return errors other than ErrNotFound. Decide before you ship whether that means “refuse to run” or “fall back to a file under os.UserConfigDir() with mode 0600”. Either is defensible if the documentation says which.

Pitfalls specific to Go

  • A zero timeout is no timeout. http.DefaultClient never gives up. Always build your own client or use contexts.
  • Close the body. Without defer res.Body.Close() the connection is not reused and file descriptors leak.
  • Reuse one *http.Client. It owns the connection pool. A new client per call throws it away.
  • Minimal containers. A scratch image has no CA certificates, so every HTTPS call fails with a certificate error. Copy a CA bundle into the image.
  • Numbers decode as float64 into map[string]any. Use structs, as above, when you read activation_usage or timestamps.

Doing this with Clavem

The License API needs no secret, so nothing sensitive ships in the binary. Plan limits never block validation. See the API reference for every field.

Questions

Does Go's http.Client return an error for a 404 or 429?

No. Do returns an error only when no response arrived, such as a network failure or a timeout. A 404 or 429 comes back as a normal response with its status, headers and body, so you read resp.StatusCode and the Retry-After header yourself.

What is the default timeout of http.Client?

None. A zero Timeout means no limit, and http.DefaultClient has none. Set Timeout on your own client, or pass a context with a deadline to every request.

Where should a Go program keep a license key?

In the system keyring through a library such as zalando/go-keyring, which needs no cgo. On Linux it needs a Secret Service such as GNOME Keyring, so a server or container has none and you need a fallback.

Sources

  1. Go net/http, Client.Timeout (checked November 2026)
  2. zalando/go-keyring README (checked November 2026)