> For the complete documentation index, see [llms.txt](https://k4k3ru.gitbook.io/k4k3ru-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://k4k3ru.gitbook.io/k4k3ru-docs/api/authentication/sign-request-with-go.md).

# Sign a Request with Go

Build an authenticated K4K3RU JSON-RPC request with Go. This example supports both `hmac-sha256` and `ed25519` credentials using only the Go standard library.

## Prerequisites

* Go 1.20 or later.
* An API credential created with `hmac-sha256` or `ed25519`.
* `K4K3RU_API_KEY`, `K4K3RU_SECRET_KEY`, and `K4K3RU_SIGNATURE_ALGORITHM` set in your environment.

## Example

Save this program as `main.go`:

```go
package main

import (
	"bytes"
	"crypto/ed25519"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"strconv"
	"strings"
	"time"
)

type auth struct {
	APIKey    string `json:"apiKey"`
	Timestamp int64  `json:"timestamp"`
	Nonce     string `json:"nonce"`
	Signature string `json:"signature"`
}

type request struct {
	ID     string          `json:"id"`
	Method string          `json:"method"`
	Params json.RawMessage `json:"params"`
	Auth   auth            `json:"auth"`
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func run() error {
	apiKey := os.Getenv("K4K3RU_API_KEY")
	secretKey := os.Getenv("K4K3RU_SECRET_KEY")
	algorithm := os.Getenv("K4K3RU_SIGNATURE_ALGORITHM")
	if apiKey == "" || secretKey == "" || algorithm == "" {
		return errors.New("set K4K3RU_API_KEY, K4K3RU_SECRET_KEY, and K4K3RU_SIGNATURE_ALGORITHM")
	}

	const method = "PaymentOnchain.CreateIntent"
	params, err := canonicalJSON([]byte(`{"productName":"usdc-base-mainnet-1"}`))
	if err != nil {
		return err
	}
	timestamp := time.Now().Unix()
	nonce, err := newNonce()
	if err != nil {
		return err
	}
	payload := strings.Join([]string{
		method,
		strconv.FormatInt(timestamp, 10),
		nonce,
		string(params),
	}, "\n")

	secret, err := base64.RawURLEncoding.DecodeString(secretKey)
	if err != nil {
		return fmt.Errorf("decode secret key: %w", err)
	}
	signature, err := sign(algorithm, secret, []byte(payload))
	if err != nil {
		return err
	}

	body, err := json.MarshalIndent(request{
		ID:     "1",
		Method: method,
		Params: params,
		Auth: auth{
			APIKey:    apiKey,
			Timestamp: timestamp,
			Nonce:     nonce,
			Signature: base64.RawURLEncoding.EncodeToString(signature),
		},
	}, "", "  ")
	if err != nil {
		return fmt.Errorf("encode request: %w", err)
	}
	fmt.Println(string(body))
	return nil
}

func canonicalJSON(raw []byte) ([]byte, error) {
	decoder := json.NewDecoder(bytes.NewReader(raw))
	decoder.UseNumber()
	var value any
	if err := decoder.Decode(&value); err != nil {
		return nil, fmt.Errorf("decode params: %w", err)
	}
	canonical, err := json.Marshal(value)
	if err != nil {
		return nil, fmt.Errorf("canonicalize params: %w", err)
	}
	return canonical, nil
}

func newNonce() (string, error) {
	value := make([]byte, 16)
	if _, err := rand.Read(value); err != nil {
		return "", fmt.Errorf("create nonce: %w", err)
	}
	return base64.RawURLEncoding.EncodeToString(value), nil
}

func sign(algorithm string, secret, payload []byte) ([]byte, error) {
	switch algorithm {
	case "hmac-sha256":
		mac := hmac.New(sha256.New, secret)
		if _, err := mac.Write(payload); err != nil {
			return nil, fmt.Errorf("sign payload: %w", err)
		}
		return mac.Sum(nil), nil
	case "ed25519":
		if len(secret) != ed25519.PrivateKeySize {
			return nil, fmt.Errorf("invalid Ed25519 private key length: %d", len(secret))
		}
		return ed25519.Sign(ed25519.PrivateKey(secret), payload), nil
	default:
		return nil, fmt.Errorf("unsupported signature algorithm: %s", algorithm)
	}
}
```

Run it with:

```bash
go run main.go
```

The program prints a request body that you can send to `https://api.k4k3ru.com/` with `Content-Type: application/json`. Replace the example product name with an active name returned by `AccountApp.ListProducts` before creating a real payment intent.

## Next Steps

See [API Request Authentication](/k4k3ru-docs/api/authentication.md) for canonicalization, freshness, replay-protection, and troubleshooting requirements.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://k4k3ru.gitbook.io/k4k3ru-docs/api/authentication/sign-request-with-go.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
