The Go SDK for SurrealDB lets you connect to a database and query it from your application. This guide covers installing the SDK, connecting, signing in, and running your first queries. When you finish, you will have code that connects to SurrealDB, creates records and reads them back.
To follow this guide, you need Go 1.24 or later and SurrealDB 3.3 or later.
1. Install the SDK
Add the SDK to your module. Its module path ends in /v2:
go get github.com/surrealdb/surrealdb.go/v2Then import the SDK and its models package. The installation guide covers the other packages of the module.
import (
"context"
"fmt"
"log"
surrealdb "github.com/surrealdb/surrealdb.go/v2"
"github.com/surrealdb/surrealdb.go/v2/pkg/models"
)The surrealdb package contains the client, the query functions and the authentication types. The models package contains value types such as RecordID and Table, which map to SurrealDB's data model.
2. Connect to SurrealDB
Use FromEndpointURLString to create a client and connect it to a SurrealDB instance. It takes a context.Context, which bounds the connection attempt, and a URL. The scheme of the URL chooses the type of connection:
WebSocket (
ws://,wss://) for long-lived stateful connections, which live queries, sessions and transactions need. A WebSocket client reconnects by itself when the connection drops.HTTP (
http://,https://) for short-lived stateless connections.
ctx := context.Background()
db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000")
if err != nil {
log.Fatal(err)
}
defer db.Close(ctx)After you connect, use .SignIn() to authenticate. Then use .Use() to select the namespace and database to work with. Most operations need both.
_, err = db.SignIn(ctx, surrealdb.Auth{
Username: "root",
Password: "secret",
})
if err != nil {
log.Fatal(err)
}
if err := db.Use(ctx, "main", "main"); err != nil {
log.Fatal(err)
}defer db.Close(ctx) closes the connection when your function returns, as you would close a file in Go.
3. Inserting data into SurrealDB
Use the Create function to create records. To let SurrealDB generate an ID, pass the table name as a string. To choose the ID yourself, pass a RecordID. The data can be a struct or a map.
type User struct {
ID *models.RecordID `json:"id,omitempty"`
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
user, err := surrealdb.Create[User](ctx, db, "users", User{
Name: "John",
Email: "john@example.com",
Age: 32,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", user)To create a record with a specific ID, use a RecordID:
type Product struct {
ID *models.RecordID `json:"id,omitempty"`
Name string `json:"name"`
Price float64 `json:"price"`
Category string `json:"category"`
}
product, err := surrealdb.Create[Product](ctx, db, models.NewRecordID("products", "apple"), Product{
Name: "Apple",
Price: 1.50,
Category: "fruit",
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", product)The Go SDK uses generic functions, such as surrealdb.Create[User](...), rather than methods on db. The type parameter tells the SDK which Go type to decode the result into.
4. Retrieving data from SurrealDB
Selecting records
The Select function reads all the records of a Table, or a single record by its RecordID. Use a slice as the type parameter for a table, and a single type for a record.
users, err := surrealdb.Select[[]User](ctx, db, models.Table("users"))
if err != nil {
log.Fatal(err)
}
fmt.Printf("All users: %+v\n", users)
apple, err := surrealdb.Select[Product](ctx, db, models.NewRecordID("products", "apple"))
if err != nil {
log.Fatal(err)
}
fmt.Printf("Apple: %+v\n", apple)Running SurrealQL queries
For more advanced queries, use the Query function to run SurrealQL statements directly. Pass values as parameters rather than writing them into the query.
results, err := surrealdb.Query[[]Product](ctx, db,
"SELECT name, price FROM products WHERE price < $max_price ORDER BY price",
map[string]any{"max_price": 5.00},
)
if err != nil {
log.Fatal(err)
}
for _, qr := range *results {
fmt.Printf("%+v\n", qr.Result)
}Query returns one result for each statement in the query.
5. Closing the connection
Close the connection when your application no longer needs it, to release its resources. In Go, the usual way is to defer the close directly after you create the connection, as in step 2. If you do not use defer, call .Close() yourself when you are done:
db.Close(ctx)Next steps
You have installed the SDK, connected to SurrealDB, created records and read them back. Other features of the SDK include updating and deleting records, authentication, live queries and transactions.
Connection management
Learn how to manage your database connections, including protocols and configuration.
Authentication
Read more about authentication levels and how to integrate them into your application.
Data manipulation
Learn how to create, read, update, and delete records using the SDK.
API reference
Complete reference for all functions, methods, types, and errors.
This guide covers the essentials. For the complete reference to the methods, the API and the concepts, see the Go SDK reference. To upgrade a project from version 1 of the SDK, see Migrating to Go SDK 2.x.