# flagbearer for Go

The Go SDK for Flagbearer. Requires Go 1.23 or later.

## Install

```sh
go get github.com/flagbearer-dev/sdks/go
```

```go
import flagbearer "github.com/flagbearer-dev/sdks/go"
```

## Keys

Use a server key, which starts with `fbs_`. Server keys are secret: read them
from the environment, such as `FLAGBEARER_SERVER_KEY`, and never put them in
browser code or in the repository. Browsers use client keys, which start with
`fbc_`, through [`@flagbearer/web`](/sdks/web).

## Sync at startup

Create one client per process, when the app starts, and wait for it to sync
before accepting requests:

```go
flags, err := flagbearer.New(os.Getenv("FLAGBEARER_SERVER_KEY"))
if err != nil {
	log.Fatal(err) // An empty key or an invalid URL.
}

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := flags.Sync(ctx); err != nil {
	// Keep starting: checks use their defaults, and the SDK retries in the background.
	log.Printf("Initial Flagbearer sync failed: %v", err)
}
```

## Check per request

Pass each request's user explicitly, and a default:

```go
func search(w http.ResponseWriter, r *http.Request) {
	user := flagbearer.User{Key: currentUser(r).ID, Email: currentUser(r).Email}
	advanced := flags.IsEnabled("advanced-search", user, false)
	// …
}
```

The email is optional. Include it to turn flags on for testers by email.
The default is used until the client has synced, and when the flag doesn't
exist.

## Shut down

Keep the client for the life of the process, not per request. Close it on
shutdown:

```go
defer flags.Close()
```

Serverless functions should call `flags.Flush(ctx)` at the end of each
invocation.
