Reputation: 81
I'm trying to import my EventController.go
to my main.go
file.
├───Controllers
│ └───Event
│ └───EventController.go
├───Models
├───Routes
│
└ Main.go
import (
"log"
"net/http"
_ "/Controllers/Event/EventController.go" //problem here
)
error : cannot import absolute path
I read some documentation but the thing is I see that I'm doing it correctly, though i learnt about $GOPATH but I want to use the local directory thing.
What am I doing wrong and what's this error about
Thank you.
Upvotes: 3
Views: 9208
Reputation: 17
Go supports package level import. You can import a package by adding it to the import statement at the beginning of the file.
In your case, you should do something like this-
import (
"log"
"net/http"
"Controllers/Event/EventController"
)
Also, you should remove first "/" from the file name
_ /Controllers/Event/EventController.go" //problem here
because your Controllers folder is at the same level as Main.go file. You should always give relative path in the import statements.
In this way, you can use any file which is listed under EventController folder.
Upvotes: -1
Reputation:
There are a few issues:
The document How to Write Go Code is a nice tutorial on how to do this.
Here's how to reorganize the code given the above. This assumes that main.go is in a package with import path "myapp". Change this import path to whatever you want.
-- main.go --
package main
import (
"log"
_ "myapp/controllers/event"
)
func main() {
log.Println("hello from main")
}
-- go.mod --
module myapp
-- controllers/event/eventController.go --
package event
import "log"
func init() {
log.Println("hello from controllers/event")
}
Run this example on the Go playground.
Upvotes: 6
Reputation: 51632
You cannot import a file. You can import a package. So, lets say your main is the package "github.com/mypackage", then you should import "github.com/mypackage/Controllers/Event".
Upvotes: 0