- Install the Go library:
go get github.com/schematichq/schematic-go
-
Issue an API key for the appropriate environment using the Schematic app. Be sure to capture the secret key when you issue the API key; you'll only see this key once, and this is what you'll use with the Schematic Go library.
-
Using this secret key, initialize a client in your Go application:
import (
"os"
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
)
func main() {
apiKey := os.Getenv("SCHEMATIC_API_KEY")
client := schematicclient.NewSchematicClient(option.WithAPIKey(apiKey))
defer client.Close()
}
By default, the client will do some local caching for flag checks, if you would like to change this behavior, you can do so using an initialization option to specify the max size of the cache (in terms of number of records) and the max age of the cache (as a time.Duration
):
import (
"os"
"time"
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
)
func main() {
apiKey := os.Getenv("SCHEMATIC_API_KEY")
cacheSize := 100
cacheTTL := 1 * time.Millisecond
client := schematicclient.NewSchematicClient(
option.WithAPIKey(apiKey),
option.WithLocalFlagCheckCache(cacheSize, cacheTTL),
)
defer client.Close()
}
You can also disable local caching entirely with an initialization option; bear in mind that, in this case, every flag check will result in a network request:
import (
"os"
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
)
func main() {
apiKey := os.Getenv("SCHEMATIC_API_KEY")
client := schematicclient.NewSchematicClient(option.WithAPIKey(apiKey), option.WithDisabledFlagCheckCache())
defer client.Close()
}
You may want to specify default flag values for your application, which will be used if there is a service interruption or if the client is running in offline mode (see below). You can do this using an initialization option:
import (
"os"
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
)
func main() {
apiKey := os.Getenv("SCHEMATIC_API_KEY")
client := schematicclient.NewSchematicClient(option.WithAPIKey(apiKey), option.WithDefaultFlagValues(map[string]bool{
"some-flag-key": true,
}))
defer client.Close()
}
A number of these examples use keys
to identify companies and users. Learn more about keys here.
Create or update users and companies using identify events.
import (
"context"
"os"
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
schematicgo "github.com/schematichq/schematic-go"
)
func main() {
apiKey := os.Getenv("SCHEMATIC_API_KEY")
client := schematicclient.NewSchematicClient(option.WithAPIKey(apiKey))
defer client.Close()
client.Identify(context.Background(), &schematicgo.EventBodyIdentify{
Event: "some-action",
Company: map[string]string{
"id": "your-company-id",
},
User: map[string]string{
"email": "wcoyote@acme.net",
"user-id": "your-user-id",
},
Name: "Wile E. Coyote",
Traits: map[string]any{
"city": "Atlanta",
"login_count": 24,
"is_staff": false,
},
})
}
This call is non-blocking and there is no response to check.
Track activity in your application using track events; these events can later be used to produce metrics for targeting.
import (
"context"
"os"
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
schematicgo "github.com/schematichq/schematic-go"
)
func main() {
apiKey := os.Getenv("SCHEMATIC_API_KEY")
client := schematicclient.NewSchematicClient(option.WithAPIKey(apiKey))
defer client.Close()
client.Track(context.Background(), &schematicgo.EventBodyTrack{
Event: "some-action",
Company: map[string]string{
"id": "your-company-id",
},
User: map[string]string{
"email": "wcoyote@acme.net",
"user-id": "your-user-id",
},
})
}
This call is non-blocking and there is no response to check.
If you want to record large numbers of the same event at once, or perhaps measure usage in terms of a unit like tokens or memory, you can optionally specify a quantity for your event:
import (
"context"
"os"
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
schematicgo "github.com/schematichq/schematic-go"
)
func main() {
apiKey := os.Getenv("SCHEMATIC_API_KEY")
client := schematicclient.NewSchematicClient(option.WithAPIKey(apiKey))
defer client.Close()
client.Track(context.Background(), &schematicgo.EventBodyTrack{
Event: "query-tokens",
Company: map[string]string{
"id": "your-company-id",
},
User: map[string]string{
"email": "wcoyote@acme.net",
"user-id": "your-user-id",
},
Quantity: schematicgo.Int(1500),
})
}
Although it is faster to create companies and users via identify events, if you need to handle a response, you can use the companies API to upsert companies. Because you use your own identifiers to identify companies, rather than a Schematic company ID, creating and updating companies are both done via the same upsert operation:
import (
"context"
"os"
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
schematicgo "github.com/schematichq/schematic-go"
)
func main() {
apiKey := os.Getenv("SCHEMATIC_API_KEY")
client := schematicclient.NewSchematicClient(option.WithAPIKey(apiKey))
defer client.Close()
body := &schematicgo.UpsertCompanyRequestBody{
Keys: map[string]string{
"id": "your-company-id",
},
Name: "Acme Widgets, Inc.",
Traits: map[string]any{
"city": "Atlanta",
"high_score": 25,
"is_active": true,
},
})
resp, err := client.API().Companies.UpsertCompany(context.Background, body)
}
You can define any number of company keys; these are used to address the company in the future, for example by updating the company's traits or checking a flag for the company. You can also define any number of company traits; these can then be used as targeting parameters.
Similarly, you can upsert users using the Schematic API, as an alternative to using identify events. Because you use your own identifiers to identify users, rather than a Schematic user ID, creating and updating users are both done via the same upsert operation:
import (
"context"
"os"
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/SchematicHQ/schematic-go/client"
schematicgo "github.com/SchematicHQ/schematic-go"
)
func main() {
apiKey := os.Getenv("SCHEMATIC_API_KEY")
client := schematicclient.NewSchematicClient(option.WithAPIKey(apiKey))
defer client.Close()
body := &schematicgo.UpsertUserRequestBody{
Keys: map[string]string{
"email": "wcoyote@acme.net",
"user-id": "your-user-id",
},
Company: map[string]string{
"id": "your-company-id",
},
Name: "Wile E. Coyote",
Traits: map[string]any{
"city": "Atlanta",
"login_count": 24,
"is_staff": false,
},
})
resp, err := client.API().Companies.UpsertUser(context.Background(), body)
}
You can define any number of user keys; these are used to address the user in the future, for example by updating the user's traits or checking a flag for the user. You can also define any number of user traits; these can then be used as targeting parameters.
When checking a flag, you'll provide keys for a company and/or keys for a user. You can also provide no keys at all, in which case you'll get the default value for the flag.
import (
"context"
"os"
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
schematicgo "github.com/schematichq/schematic-go"
)
func main() {
apiKey := os.Getenv("SCHEMATIC_API_KEY")
client := schematicclient.NewSchematicClient(option.WithAPIKey(apiKey))
defer client.Close()
evaluationCtx := schematicgo.CheckFlagRequestBody{
Company: map[string]string{
"id": "your-company-id",
},
User: map[string]string{
"email": "wcoyote@acme.net",
"user-id": "your-user-id",
},
}
if client.CheckFlag(context.Background(), "some-flag-key", evaluationCtx) {
// Flag is on
} else {
// Flag is off
}
}
The Schematic API supports many operations beyond these, accessible via client.API()
. See the API submodule readme for a full list and documentation of supported operations.
In development or testing environments, you may want to avoid making network requests to the Schematic API. You can run Schematic in offline mode by not providing an API key to the client:
import (
schematicclient "github.com/schematichq/schematic-go/client"
)
func main() {
client := schematicclient.NewSchematicClient()
defer client.Close()
}
You can also enable offline mode by providing an empty API key:
import (
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
)
func main() {
client := schematicclient.NewSchematicClient(option.WithAPIKey(""))
defer client.Close()
}
Or, by using the offline mode option:
import (
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
)
func main() {
client := schematicclient.NewSchematicClient(option.WithOfflineMode())
defer client.Close()
}
Offline mode works well with flag defaults:
import (
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
)
func main() {
client := schematicclient.NewSchematicClient(option.WithOfflineMode(), option.WithDefaultFlagValues(map[string]bool{
"some-flag-key": true,
}))
defer client.Close()
}
In an automated testing context, you may also want to use offline mode and specify single flag responses for test cases:
import (
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
)
func TestSomeFunctionality(t *testing.T) {
client := schematicclient.NewSchematicClient(option.WithOfflineMode())
defer client.Close()
client.SetFlagDefault("some-flag-key", true)
// test code that expects the flag to be on
}
Schematic can send webhooks to notify your application of events. To ensure the security of these webhooks, Schematic signs each request using HMAC-SHA256. The Go SDK provides utility functions to verify these signatures.
When your application receives a webhook request from Schematic, you should verify its signature to ensure it's authentic. The SDK provides a simple function to verify webhook signatures:
import (
"net/http"
"github.com/schematichq/schematic-go/webhooks"
)
func yourWebhookHandler(w http.ResponseWriter, r *http.Request) {
// Each webhook has a distinct secret; you can access this via the Schematic app
webhookSecret := "your-webhook-secret"
// Verify the webhook signature
// The request body is preserved for later reading
err := webhooks.VerifyWebhookSignature(r, webhookSecret)
if err != nil {
// The signature is invalid or there was another error
http.Error(w, "Invalid signature", http.StatusBadRequest)
return
}
// The signature is valid, process the webhook...
}
If you want to verify a webhook signature outside of the context of a web request, you can also do that using the webhooks.VerifySignature
function.
The DataStream
functionality in Schematic provides real-time updates for flags, companies, and users. It uses WebSocket connections to receive updates from the Schematic backend and caches the data locally or in Redis for efficient access.
- Real-Time Updates: Automatically updates cached data when changes occur on the backend.
- Configurable Caching: Supports both in-memory (local) caching and Redis-based caching.
- Efficient Flag Checks: Flag evaluation happens locally reducing number of network calls.
To enable the DataStream
functionality, you need to pass the WithDatastream
option when creating a new SchematicClient
.
import (
schematicclient "github.com/schematichq/schematic-go/client"
schematicoption "github.com/schematichq/schematic-go/option"
)
func main() {
apiKey := "your-api-key"
options := &core.DatastreamOptions{
CacheTTL: 5 * time.Minute, // Set the cache TTL (time-to-live)
}
client := schematicclient.NewSchematicClient(
schematicoption.WithAPIKey(apiKey),
schematicoption.WithDatastream(options),
)
defer client.Close()
}
The DataStream
functionality supports Redis for caching company and user data. You can configure it to use either a single Redis instance or a Redis cluster.
To use a single Redis instance, create a RedisCacheConfig
and pass it to the DatastreamOptions
.
options := &schematicoption.DatastreamOptions{
CacheTTL: 5 * time.Minute, // Set the cache TTL
CacheConfig: &schematicoption.RedisCacheConfig{
Addr: "localhost:6379", // Redis server address
Password: "", // Redis password (if any)
DB: 0, // Redis database index
MaxRetries: 3, // Number of retries for failed operations
DialTimeout: 5 * time.Second, // Connection timeout
ReadTimeout: 3 * time.Second, // Read timeout
WriteTimeout: 3 * time.Second, // Write timeout
},
}
To use a Redis cluster, create a RedisCacheClusterConfig
and pass it to the DatastreamOptions
.
options := &schematicoption.DatastreamOptions{
CacheTTL: 5 * time.Minute, // Set the cache TTL
CacheConfig: &schematicoption.RedisCacheClusterConfig{
Addrs: []string{"localhost:7000", "localhost:7001", "localhost:7002"}, // Cluster node addresses
Password: "", // Redis password (if any)
MaxRetries: 3, // Number of retries for failed operations
DialTimeout: 5 * time.Second, // Connection timeout
ReadTimeout: 3 * time.Second, // Read timeout
WriteTimeout: 3 * time.Second, // Write timeout
RouteByLatency: true, // Route requests to the node with the lowest latency
RouteRandomly: false, // Disable random routing
},
}
Structured error types are returned from API calls that return non-success status codes. For example, you can check if the error was due to an unauthorized request (i.e. status code 401) with the following:
import (
"context"
"os"
core "github.com/schematichq/schematic-go/core"
option "github.com/schematichq/schematic-go/option"
schematicclient "github.com/schematichq/schematic-go/client"
schematicgo "github.com/schematichq/schematic-go"
)
func main() {
apiKey := os.Getenv("SCHEMATIC_API_KEY")
client := schematicclient.NewSchematicClient(option.WithAPIKey(apiKey))
defer client.Close()
body := &schematicgo.UpsertCompanyRequestBody{
Keys: map[string]string{
"id": "your-company-id",
},
Name: "Acme Widgets, Inc.",
Traits: map[string]any{
"city": "Atlanta",
"high_score": 25,
"is_active": true,
},
})
resp, err := client.API().Companies.UpsertCompany(context.Background, body)
if err != nil {
if apiError, ok := err.(*core.APIError); ok {
switch (apiError.StatusCode) {
case http.StatusUnauthorized:
// Do something with the unauthorized request ...
}
}
return err
}
}
These errors are also compatible with the errors.Is
and errors.As
APIs, so you can access the error
like so:
if err != nil {
var apiError *core.APIError
if errors.As(err, apiError) {
// Do something with the API error ...
}
return err
}