Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang import cycle not allowed

Tags:

go

I am creating a restful api in GO and every method essentially interacts with the database. The specific statement that I use to open a database connection is

db,err := sql.Open("postgres", "user=postgres password=password dbname=dbname sslmode=disable")
    if err != nil {
        log.Fatal(err)
        println(err)

    }

It is very simple but the issue is that once I want to change something inside that statement then I have to change it for all other methods that have that statement . I am trying to do a dependency injection or something of that nature so that I can have that statement or value in 1 place and just reference it. I am getting an import cycle not allowed error though like Import cycle not allowed . This is my project structure

enter image description here

What I have done is that in the Config.go I have written this

package Config

const Connect  = "user=postgres password=password dbname=dbname sslmode=disable"

Then in the Listings.go I put this

package Controllers

import (
    "net/http"
    "database/sql"

       "../Config"

)

func Listing_Expiration(w http.ResponseWriter, r *http.Request)  {


        db,err := sql.Open("postgres",Config.Connect)

        if err != nil {
            log.Fatal(err)
            println(err)

}

notice I have the import ../Config and the Config.Connect but when I compile that I get import cycle not allowed . I have been trying to solve this issue but haven't been able to.

like image 358
user1591668 Avatar asked Jul 16 '16 16:07

user1591668


2 Answers

Yes, Go doesn't allow to have cycled imports. In your example you have 2 packages Config and Controllers. When you build a code, Controllers package requires Config package, then Config requires Controllers and it's endless. You should refactor your code to make Config package separated from Controllers, and only used by it. Also, you can make some common package, imported to Controllers and Config.

like image 60
Alex Pliutau Avatar answered Oct 20 '22 16:10

Alex Pliutau


I got the same error. But in my case, I imported the package itself inside the file. so you can check if you did the same mistake.

like image 37
VithuBati Avatar answered Oct 20 '22 16:10

VithuBati