packagemainimport("context""io""log""os""github.com/gagliardetto/solana-go""github.com/mr-tron/base58""github.com/openlibx402/go/openlibx402-client")funcmain(){// Load wallet from environmentprivateKeyStr:=os.Getenv("X402_PRIVATE_KEY")ifprivateKeyStr==""{log.Fatal("X402_PRIVATE_KEY not set")}// Decode private keyprivateKeyBytes:=base58.Decode(privateKeyStr)walletKeypair:=solana.PrivateKey(privateKeyBytes)// Create auto client (automatically handles 402 and pays)client:=client.NewAutoClient(walletKeypair,"",&client.AutoClientOptions{MaxPaymentAmount:"10.0",// Safety limitAutoRetry:true,// Auto-pay on 402})deferclient.Close()ctx:=context.Background()// Access premium endpoint (automatically pays if needed)log.Println("Accessing premium endpoint...")resp,err:=client.Get(ctx,"https://api.example.com/api/premium")iferr!=nil{log.Fatal(err)}deferresp.Body.Close()// Read responsedata,_:=io.ReadAll(resp.Body)log.Printf("Response: %s",string(data))}
# If you have a Solana wallet filesolana-keygenshow--private-key
# Output will be base58 encoded private key# Export itexportX402_PRIVATE_KEY="your-base58-private-key"
// POST requestdata:=[]byte(`{"name": "value"}`)resp,err:=client.Post(ctx,"https://api.example.com/data",data)// PUT requestresp,err:=client.Put(ctx,"https://api.example.com/data",data)// DELETE requestresp,err:=client.Delete(ctx,"https://api.example.com/data")
// Different endpoints with different pricingendpoints:=map[string]string{"basic":"https://api.example.com/basic","premium":"https://api.example.com/premium","ultimate":"https://api.example.com/ultimate",}forname,endpoint:=rangeendpoints{log.Printf("Accessing %s endpoint...",name)resp,err:=client.Get(ctx,endpoint)iferr!=nil{log.Printf("Error accessing %s: %v",name,err)continue}data,_:=io.ReadAll(resp.Body)resp.Body.Close()log.Printf("%s response: %s",name,string(data))}
// ✅ Good: Always use payment limitclient:=client.NewAutoClient(walletKeypair,"",&client.AutoClientOptions{MaxPaymentAmount:"10.0",// Prevent accidental overpayment})// ✅ Good: Always closedeferclient.Close()// ✅ Good: Use context with timeoutctx,cancel:=context.WithTimeout(context.Background(),30*time.Second)defercancel()// ❌ Bad: No safety limitsclient:=client.NewAutoClient(walletKeypair,"",nil)// ❌ Bad: AllowLocal in productionclient:=client.NewAutoClient(walletKeypair,"",&client.AutoClientOptions{AllowLocal:true,// Only for development!})