> ## Documentation Index
> Fetch the complete documentation index at: https://shinydapps-bd9fa40b.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Go SDK

> Complete reference for the l402-kit Go SDK � net/http middleware for Bitcoin Lightning pay-per-call APIs.

## Installation

```bash theme={null}
go get github.com/shinydapps/l402-kit/go@v1.10.0
```

**Requirements**: Go 1.21+

***

## Quickstart

```go theme={null}
package main

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

    l402 "github.com/shinydapps/l402-kit/go"
)

func main() {
    lightning := l402.NewBlinkProvider(
        os.Getenv("BLINK_API_KEY"),
        os.Getenv("BLINK_WALLET_ID"),
    )

    mux := http.NewServeMux()
    mux.Handle("/api/data", l402.Middleware(l402.Options{
        PriceSats: 10,
        Lightning: lightning,
    }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(map[string]string{"data": "premium content"})
    })))

    http.ListenAndServe(":8080", mux)
}
```

Get Blink credentials free at [dashboard.blink.sv](https://dashboard.blink.sv). Payments go directly to your wallet.

***

## Self-hosted mode (bring your own provider)

```go theme={null}
import l402 "github.com/shinydapps/l402-kit/go"

type MyProvider struct{}

func (p *MyProvider) CreateInvoice(ctx context.Context, amountSats int) (l402.Invoice, error) {
    // create invoice with your Lightning node
    // return l402.Invoice{PaymentRequest: "lnbc...", PaymentHash: "...", Macaroon: "..."}
}

mux.Handle("/api/data", l402.Middleware(l402.Options{
    PriceSats: 10,
    Lightning: &MyProvider{},
}, handler))
```

***

## `l402.Options`

| Field       | Type                   | Default      | Description                                     |
| ----------- | ---------------------- | ------------ | ----------------------------------------------- |
| `PriceSats` | `int`                  | **required** | Price per call in satoshis                      |
| `Lightning` | `LightningProvider`    | **required** | Your Lightning backend (use `NewBlinkProvider`) |
| `OnPayment` | `func(L402Token, int)` | �            | Callback fired after each verified payment      |

***

## `l402.Middleware(opts Options, next http.Handler) http.Handler`

Returns an `http.Handler` compatible with `net/http`, Chi, Gorilla Mux, and any standard Go HTTP framework.

### Behavior

| Request                            | Response                                                           |
| ---------------------------------- | ------------------------------------------------------------------ |
| No `Authorization` header          | `402` + `WWW-Authenticate: L402 macaroon="...", invoice="lnbc..."` |
| Valid `L402 <macaroon>:<preimage>` | `next.ServeHTTP(w, r)`                                             |
| Invalid or expired token           | `401 Unauthorized`                                                 |
| Replayed preimage                  | `401 Token already used`                                           |

### 402 response body

```json theme={null}
{
  "error": "Payment Required",
  "invoice": "lnbc100n1...",
  "macaroon": "eyJoYXNoIjoiYWJjMTIzIiwiZXhwIjoxNzAwMDAwMDAwfQ==",
  "price_sats": 10
}
```

***

## `LightningProvider` interface

```go theme={null}
type LightningProvider interface {
    CreateInvoice(ctx context.Context, amountSats int) (Invoice, error)
}
```

***

## `OnPayment` callback

```go theme={null}
lightning := l402.NewBlinkProvider(os.Getenv("BLINK_API_KEY"), os.Getenv("BLINK_WALLET_ID"))

mux.Handle("/api/data", l402.Middleware(l402.Options{
    PriceSats: 10,
    Lightning: lightning,
    OnPayment: func(token l402.L402Token, amountSats int) {
        log.Printf("payment: %d sats, preimage: %s", amountSats, token.Preimage)
    },
}, handler))
```

***

## Verification

`SHA256(preimage) == paymentHash` is verified locally in memory � **sub-millisecond, no network call** on the hot path. Token expiry (`exp` field in the macaroon) is checked in the same operation.

The replay guard uses an in-memory map by default (safe for a single process). For multi-instance deployments, use a shared store (Redis or similar) � which adds a **5�50 ms** round-trip per verified request.

***

## Chi router example

`l402.Middleware` returns a standard `http.Handler`, so it works directly with Chi's `r.Handle`:

```go theme={null}
import (
    "github.com/go-chi/chi/v5"
    l402 "github.com/shinydapps/l402-kit/go"
)

r := chi.NewRouter()
lightning := l402.NewBlinkProvider(os.Getenv("BLINK_API_KEY"), os.Getenv("BLINK_WALLET_ID"))

r.Handle("/api/data", l402.Middleware(l402.Options{
    PriceSats: 10,
    Lightning: lightning,
}, http.HandlerFunc(handler)))
```

***

## Error codes

| Status | Meaning                                |
| ------ | -------------------------------------- |
| `402`  | No payment token � pay the invoice     |
| `401`  | Invalid token or expired macaroon      |
| `401`  | Replayed token (preimage already used) |

***

## Running

```bash theme={null}
go run main.go

# Test � triggers 402
curl http://localhost:8080/api/data

# Pay invoice, then:
curl -H "Authorization: L402 <macaroon>:<preimage>" http://localhost:8080/api/data
```
