Setting up Neo4J with Golang

Viewed 336

I am setting up Go with Neo4j on a live project for one of the microservices

I went through the docs around setting up the same but it does not show the best practice to do the same (specifically globally and pass around the session instance throughout the application)

This is what I am doing to setup the same, was wondering if this is the right approach:

// app.go

import ""github.com/neo4j/neo4j-go-driver/neo4j""

type App struct {
    Router *mux.Router
    DB *sqlx.DB
    Neo4j neo4j.Session // setting neo4j session globally for injection
}

// =============================
// Neo4j initialization 
// =============================
    driver, err2 := neo4j.NewDriver(
        neo4jConfig.connstring,
        neo4j.BasicAuth(neo4jConfig.username, neo4jConfig.password, ""),
        func(c *neo4j.Config){
            c.Encrypted = false
        },
    )
    checkForErrors(err2, "Cannot connect to NEO4J")
    defer driver.Close()
    session, err3 := driver.NewSession(neo4j.SessionConfig{})
    a.Neo4j = session //  assigning the session instance

Now this will be injected as a dependency in the repo package where the queries are being executed

1 Answers

The example in the readme says the following:

// Sessions are short-lived, cheap to create and NOT thread safe. Typically create one or more sessions
// per request in your web application. Make sure to call Close on the session when done.
// For multi-database support, set sessionConfig.DatabaseName to requested database
// Session config will default to write mode, if only reads are to be used configure session for
// read mode.
session := driver.NewSession(neo4j.SessionConfig{})

So having a global driver instance is not an issue, but you should not be using a global session instance since it is not thread safe.

Related