Go quick start

Use Fauna’s Go driver to query e-commerce demo data in a Go app. The driver requires Go 1.19 or later.

 

  1. Create a database with demo data

    Log in to the Fauna Dashboard, and create a database with the following configuration:

    • Region group: Choose your preferred region group, which determines where your data resides.

    • Use demo data: Enabled.

    • Enable backups: Disabled.

    Leave the other options as is.

    Create demo database

  2. Create an authentication secret

    Fauna supports several types of authentication secrets. Create a key, which is a type of secret, with the built-in server-readonly role:

    1. In the Dashboard’s Explorer page, select your demo database.

    2. In the database’s Keys tab, click Create Key.

    3. Choose a Role of server (read-only).

    4. Click Save.

    5. Copy the Key Secret.

    Create a key

  3. Set the FAUNA_SECRET environment variable

    Set the FAUNA_SECRET environment variable to your key’s secret. Fauna’s client drivers can access the secret from this variable.

    export FAUNA_SECRET=<KEY_SECRET>
  4. Install the Go driver

    Create a new directory for your app and install the Go driver:

    mkdir app
    cd app
    go mod init app
    go get github.com/fauna/fauna-go/v3
  5. Create a basic app

    In the app directory, create an app.go file and add the following code:

    package main
    
    import (
    	"fmt"
    
    	"github.com/fauna/fauna-go/v3"
    )
    
    func main() {
    	// Initialize the client to connect to Fauna
    	// using the `FAUNA_SECRET` environment variable.
    	client, clientErr := fauna.NewDefaultClient()
    	if clientErr != nil {
    		panic(clientErr)
    	}
    
    	// Compose a query using an FQL template string.
    	// The query calls the `Product` collection's
    	// `sortedByPriceLowToHigh()` index. It projects the `name`,
    	// `description`, and `price` fields covered by the index.
    	query, _ := fauna.FQL(`
    		Product.sortedByPriceLowToHigh() {
    			name,
    			description,
    			price
    			}
    	`, nil)
    
    	// Run the query.
    	paginator := client.Paginate(query)
    
    	// Iterate through the results.
    	for {
    		page, _ := paginator.Next()
    
    		var pageItems []any
    		page.Unmarshal(&pageItems)
    
    		for _, item := range pageItems {
    			jsonData, _ := json.Marshal(item)
    			fmt.Println(string(jsonData))
    		}
    
    		if !paginator.HasNext() {
    			break
    		}
    	}
    }
  6. Run the app

    Run the script from the app directory. The script prints a list of e-commerce products from the demo data in the terminal.

    go run app.go
\