Reputation: 499
I'm currently using Go 1.12 modules and really tired about importing.
I'm making the rest-api using gin(web microservices) and gorm(golang orm). Everything still ok while working in golang modules. But getting trouble with local packages importing
The directory tree:
The go.mod:
module github.com/Aragami1408/go-gorm
go 1.12
require (
github.com/gin-gonic/gin v1.4.0
github.com/jinzhu/gorm v1.9.9
github.com/lib/pq v1.1.1
github.com/satori/go.uuid v1.2.0
)
The db.go:
package db
//code below...
The tasks.go:
package task
import (
"../db"
)
But when I run and still get this error:
local import "../db" in non-local package
I've searched a lot on google and nothing helps
Upvotes: 2
Views: 3383
Reputation: 93163
When migrating to go as "package manager", you may create the file go mod
using the command :
go mod init myhost/myrepo/mymodule
Then the file will be created go.mod
will be created :
module myhost/myrepo/mymodule
go 1.15
Now you can leverage this file to list your dependencies to other modules :
# i.e: your module mymodule depends on github.com/gorilla/mux
go get github.com/gorilla/mux
You run it? then check again the content of go.mod
module myhost/myrepo/mymodule
go 1.15
require (
github.com/gorilla/mux v1.7.4
)
However, you forget that you need to maintain all go files which imports directories with relative paths.
example :
if you have main.go
package main
import (
"fmt"
"./router" // !! RELATIVE PATH
)
You must migrate also by replacing the relative path with [module-name]/relative-path
. in this case, it must become :
package main
import (
"fmt"
"myhost/myrepo/mymodule/router" // !! 💼 No more RELATIVE PATH
)
Upvotes: 1
Reputation: 251
If you are using go modules you can replace your package by a local one using:
go mod edit -replace github.com/username/project=/localpath
then just call
go get github.com/username/project
and everything should work fine.
Upvotes: 2
Reputation: 1323115
From "Do modules work with relative imports like import "./subdir"?"
In modules, there finally is a name for the subdirectory.
If the parent directory says "
module m
" then the subdirectory is imported as "m/subdir
", no longer "./subdir
".
In your case:
import "github.com/Aragami1408/go-gorm/db"
# or maybe
import "go-gorm/db"
This assumes, as commented below by Silvio Lucas, that you have set GO111MODULE=on
.
Upvotes: 5