doushou9028 2016-07-16 16:03
浏览 80

Golang导入周期不允许

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.

  • 写回答

2条回答 默认 最新

  • dongwen7423 2016-07-16 16:30
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题