Register for Neon Developer Days 🚀Read More
Guides

Connect a Go application to Neon

This topic describes how to create a Neon project and connect to it from a Go application.

To connect to Neon from a Go application:

  1. Create a Neon project
  2. Configure Go project connection settings

Create a Neon project

When creating a Neon project, take note of your user name, password, database name, and project ID. This information is required when defining connection settings in your Go application.

To create a Neon project:

  1. Navigate to the Projects page in the Neon Console.
  2. Click New Project.
  3. Specify a name, a PostgreSQL version, a region, and click Create Project.

For additional information about creating projects, see Setting up a project.

Configure Go application connection settings

Connecting to Neon requires configuring connection settings in your Go project's .go file.

note

Neon is fully compatible with the sql/db package and common PostgreSQL drivers, such as lib/pq and pgx.

Specify the connection settings for your Neon project in your .go file, as shown in the following example:

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq"
)

func main() {
    connStr := "user=<user> password=<password> dbname=main host=<endpoint_hostname>"
    db, err := sql.Open("postgres", connStr)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    rows, err := db.Query("select version()")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    var version string
    for rows.Next() {
        err := rows.Scan(&version)
        if err != nil {
            log.Fatal(err)
        }
    }
    fmt.Printf("version=%s\n", version)
}

where:

  • <user> is the database user, which is found on the Neon Dashboard, under Connection Details.
  • <password> is the database user's password, which is provided to you when you create a project.
  • <dbname> is the name of the database in your Neon project. main is the default database created with each Neon project.
  • <endpoint_hostname> is the hostname of the branch endpoint, which is found on the Neon Dashboard, under Connection Settings.

The .go file example shown above is also available on The Go Playground.

Edit this page
Was this page helpful?