简体   繁体   中英

How do I fix this import?

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM