Using Supabase in Go

Supabase is an open-source platform that provides functionalities similar to Firebase but is based on PostgreSQL. In this article, we will see how to interact with Supabase using the Go language.

Configuring Supabase

Access the Supabase dashboard and create a new project. Once created, go to the API section to obtain the URL and the anonymous key (anon key).

Installing the Go client

To interact with Supabase in Go, we can use an HTTP library like resty. Install it with the command:

go get github.com/go-resty/resty/v2

Authenticating with Supabase

To make authenticated requests, we need to include the API key in the request headers:

package main

import (
	"fmt"
	"github.com/go-resty/resty/v2"
)

const (
	supabaseURL = "https://your-project.supabase.co"
	supabaseKey = "your-anon-key"
)

func main() {
	client := resty.New()
	resp, err := client.R().
		SetHeader("apikey", supabaseKey).
		SetHeader("Authorization", "Bearer "+supabaseKey).
		Get(supabaseURL + "/rest/v1/your_table")

	if err != nil {
		fmt.Println("Request error:", err)
		return
	}

	fmt.Println("Response:", resp.String())
}

Inserting data

To add a new record to the database:

resp, err := client.R().
	SetHeader("apikey", supabaseKey).
	SetHeader("Authorization", "Bearer "+supabaseKey).
	SetHeader("Content-Type", "application/json").
	SetBody(`{"name": "Mario", "surname": "Rossi"}`).
	Post(supabaseURL + "/rest/v1/your_table")

Updating data

To update an existing record:

resp, err := client.R().
	SetHeader("apikey", supabaseKey).
	SetHeader("Authorization", "Bearer "+supabaseKey).
	SetHeader("Content-Type", "application/json").
	SetBody(`{"surname": "Bianchi"}`).
	Patch(supabaseURL + "/rest/v1/your_table?id=eq.1")

Deleting data

To delete a record:

resp, err := client.R().
	SetHeader("apikey", supabaseKey).
	SetHeader("Authorization", "Bearer "+supabaseKey).
	Delete(supabaseURL + "/rest/v1/your_table?id=eq.1")

Conclusion

In this article, we have seen how to interact with Supabase using Go. With just a few simple steps, it is possible to connect to a PostgreSQL database, perform CRUD operations, and manage authentication.

Back to top