I'm building a golang backend using gorilla/mux and gocql. My objective is to create a session to a remote cassandra and share the very same session to a serie of handlers.
I came out with this implementation:
server.go:
package main
import (
"fmt"
"net/http"
"os"
"github.com/andream16/price-probe-go/api/item/rest"
"github.com/andream16/price-probe-go/cassandra"
"github.com/gorilla/mux"
)
func main() {
fmt.Println("Initializing Cassandra connection . . .")
s, err := cassandra.InitCassandraClient()
if err != nil {
fmt.Println("Unable to set up Cassandra client!")
os.Exit(1)
}
fmt.Println("Successfully initialized Cassandra connection . . .")
fmt.Println("Starting server . . .")
router := mux.NewRouter()
router.HandleFunc("/item", itemrest.ItemHandler(&s))
. . .
}
I create a new HandleFunc
for each route and pass it &s
.
And each handler is like:
func ItemHandler(session *gocql.Session) func(w http.ResponseWriter, r *http.Request) { }
Is there a more elegant way to achieve this?