Go implementation of the X402 protocol for enabling AI agents and APIs to autonomously pay for services using HTTP 402 "Payment Required" and Solana blockchain micropayments.
This repository contains the following packages:
- openlibx402-core - Core protocol implementation with models, errors, and Solana payment processing
- openlibx402-client - HTTP client with automatic and explicit payment handling
- openlibx402-nethttp - Middleware for standard Go
net/httppackage - openlibx402-echo - Middleware for Echo web framework
# Core package
go get github.com/openlibx402/go/openlibx402-core
# Client package
go get github.com/openlibx402/go/openlibx402-client
# net/http middleware
go get github.com/openlibx402/go/openlibx402-nethttp
# Echo middleware
go get github.com/openlibx402/go/openlibx402-echopackage main
import (
"encoding/json"
"net/http"
nethttp "github.com/openlibx402/go/openlibx402-nethttp"
)
func main() {
// Initialize X402
nethttp.InitX402(&nethttp.Config{
PaymentAddress: "YOUR_WALLET_ADDRESS",
TokenMint: "USDC_MINT_ADDRESS",
Network: "solana-devnet",
AutoVerify: true,
})
// Protected endpoint
http.Handle("/premium-data", nethttp.PaymentRequired(nethttp.PaymentRequiredOptions{
Amount: "0.10",
Description: "Premium market data",
})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]string{"data": "premium content"})
})))
http.ListenAndServe(":8080", nil)
}package main
import (
"context"
"io"
"log"
"github.com/gagliardetto/solana-go"
client "github.com/openlibx402/go/openlibx402-client"
)
func main() {
// Load your wallet keypair
walletKeypair := solana.NewWallet()
// Create auto client
c := client.NewAutoClient(walletKeypair.PrivateKey, "", &client.AutoClientOptions{
MaxPaymentAmount: "10.0",
AutoRetry: true,
})
defer c.Close()
// Automatically handles 402 and pays
resp, err := c.Get(context.Background(), "https://api.example.com/premium-data")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
log.Println(string(data))
}Each package has its own README with detailed documentation:
- openlibx402-core - Core protocol types and Solana integration
- openlibx402-client - HTTP client implementation
- openlibx402-nethttp - net/http middleware
- openlibx402-echo - Echo framework middleware
MIT License - See LICENSE for details