dongtang1966 2018-09-28 15:39
浏览 36
已采纳

如何修复此导入?

main_test.go

package main_test

import (
    "log"
    "os"
    "testing"
    "."
)

func TestMain(m *testing.M) {
    a = main.App{}
    a.Init(
        os.Getenv("TEST_DB_USERNAME"),
        os.Getenv("TEST_DB_PASSWORD"),
        os.Getenv("TEST_DB_NAME"))

    ensureTableExists()
    code := m.Run()
    clearTable()
    os.Exit(code)
}

app.go

package main

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

    "github.com/gorilla/mux"
    _ "github.com/lib/pq"
)

type App struct {
    Router *mux.Router
    DB *sql.DB
}

func (a *App) Init(user, password, dbname string) {

    connection := fmt.Sprintf("user=%s password=%s dbname=%s", user, password, dbname)
    var err error
    a.DB, err = sql.Open("postgres", connection)
    if err != nil {
        log.Fatal(err)
    }
    a.Router = mux.NewRouter()

}
func (a *App) Run(addr string) { }

main.go

package main

import "os"

func main() {
    a := App{}
    a.Init(
        os.Getenv("APP_DB_USERNAME"),
        os.Getenv("APP_DB_PASSWORD"),
        os.Getenv("APP_DB_NAME"))
    a.Run(":8080")
}

Hey everyone, I am brand new to Golang and working with some tutorials. In the tutorial, they are using the import statement "." which is throwing an error for me. The exact error is "Non-canonical import-path." I tried using a relative path and full path to access the main file in my project but when I use anything other than "." the var a.main.App throws an error saying that main is an unresolved type. My $GOPATH is set to c:/users/me/go/src my project lives in the src folder. I am not entirely sure what is wrong my code at the moment. If it is something glaringly obvious I apologize.

Here is what I am trying to import. This lives in a file called app.go which is called through main.go

type App struct {
    Router *mux.Router
    DB *sql.DB
}
  • 写回答

1条回答 默认 最新

  • dongyaobo9081 2018-09-28 16:46
    关注

    You don't need to import main for using struct App. You simply change the package of main_test to main then you can able to use that struct, like below i simply passed the main_test file.

    package main
    
    import (
        "os"
        "testing"
    )
    
    func TestMain(m *testing.M) {
        a := App{}
        a.Init(
            os.Getenv("TEST_DB_USERNAME"),
            os.Getenv("TEST_DB_PASSWORD"),
            os.Getenv("TEST_DB_NAME"))
    
        ensureTableExists()
        code := m.Run()
        clearTable()
        os.Exit(code)
    }
    

    Here what i get from execute the test:

    Success: Tests passed.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来