# Go

> Embed the Muzekit editor in Go: a net/http handler opens the session with the standard library, no packages needed.

<Callout title="Let your coding agent do it">Connect Claude Code, Cursor or Codex to the [MCP server](/docs/mcp#set-up-the-editor-in-your-app) and ask: "Set up the Muzekit editor in this Go app." It writes these same files.</Callout>

## How it works in Go

Since Go 1.22, `ServeMux` patterns take a method, so `POST /api/muzekit-session` matches POST only. `currentUser(r)` stands for your auth: a session cookie with gorilla/sessions or scs, or a JWT middleware that puts the user in the request context. The handler returns only the `client_secret`, never Muzekit's whole answer.

## 1. Add your secret key

[Create an editor](/signup) and copy its Test key (`mk_test_…`) from **API keys** in the dashboard. Put it in `.env` on your server:

```bash tab=".env"
MUZEKIT_SECRET_KEY=mk_test_…
```

<Screenshot src="/docs/1-embed-code.webp" original="/docs/raw/1-embed-code.png" alt="The Embed code page in the Muzekit dashboard: the Test key for the server, then the session route and mount code" />

## 2. Open a session on your server

Opens a session; register it: http.HandleFunc("POST /api/muzekit-session", muzekitSession), in `muzekit.go`:

```go tab="muzekit.go"
package main

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

func muzekitSession(w http.ResponseWriter, r *http.Request) {
	user := currentUser(r) // Your signed-in user: replace with your own auth
	if user == nil {
		http.Error(w, "Sign in first", http.StatusUnauthorized)
		return
	}
	body, _ := json.Marshal(map[string]any{"user": map[string]string{"id": user.ID, "name": user.Name, "email": user.Email}, "mode": "design"})
	req, _ := http.NewRequest("POST", "https://api.muzekit.com/v1/sessions", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("MUZEKIT_SECRET_KEY"))
	req.Header.Set("Content-Type", "application/json")
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	defer res.Body.Close()
	var session struct {
		ClientSecret string `json:"client_secret"`
	}
	json.NewDecoder(res.Body).Decode(&session)
	if res.StatusCode >= 300 || session.ClientSecret == "" {
		http.Error(w, "Muzekit refused the session", res.StatusCode)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{"client_secret": session.ClientSecret})
}
```

## 3. Mount the editor

The editor, in `your editor page or template`:

```html tab="your editor page or template"
<div id="muzekit-editor" style="height: 720px"></div>
<script src="https://muzekit.com/sdk/v1.js"></script>
<script>
  const editor = Muzekit.mount("#muzekit-editor", {
    fetchClientSecret: () =>
      fetch("/api/muzekit-session", { method: "POST" })
        .then((r) => r.json())
        .then((s) => s.client_secret),
    on: {
      ready: () => console.log("Muzekit editor ready"),
      save: (e) => console.log("Saved", e.template, e.revision),
      error: (e) => console.error("Muzekit", e.code, e.message),
    },
  });
</script>
```

## 4. Run it

```bash
go run .
```

Sign in, then open `http://localhost:8080/editor`. The editor loads in its container and the first session shows on your dashboard's Home. With a Test key, sessions on `localhost` and `127.0.0.1` are free.

## Common problems

### currentUser is undefined

It's a placeholder for your auth: read the user from `r.Context()` if your middleware stores it there.

### chi, Gin or Echo

Register the same function: `r.Post(...)` in chi, `gin.WrapF(muzekitSession)` in Gin, `echo.WrapHandler(http.HandlerFunc(muzekitSession))` in Echo.

### No timeout on the call

In production, use an `http.Client` with a `Timeout` instead of `http.DefaultClient`.

## Notes

- Secret key: MUZEKIT_SECRET_KEY goes in .env (or your secret store) on the server only. Never in browser code, never committed.
- Every user.id is your own id for that person: their designs and uploads follow it across sessions.
- mode: "design" opens the full editor; "fill" opens a form over a template (send template: "`<key or tpl_ id>`" too).
- Give the container a real height: the editor fills it.

## Deploy and go live

Build one binary and set `MUZEKIT_SECRET_KEY` in its environment: `Environment=` in a systemd unit, Docker, or Fly secrets.

Then make a Live key (`mk_live_…`), add your domain to Live under [Allowed domains](/docs/allowed-domains) and use **Copy to Live** for your templates, look and features.

## Questions

### What about Go before 1.22?

Register with `http.HandleFunc("/api/muzekit-session", muzekitSession)` and check `r.Method == http.MethodPost` yourself.

<Cards>
  <Card title="Editor modes" description="Design, fill-in and view, and what each shows." href="/docs/editor-modes" />
  <Card title="Browser SDK" description="Events, saving from your own button, and destroy." href="/docs/embed-sdk" />
</Cards>
