How to import files from current directory in go-ThrowExceptions

Exception or error:

Intro

I’m trying to import my EventController.go to my main.go file.

Directory:


├───Controllers
│    └───Event
│        └───EventController.go
├───Models
├───Routes
│
└ Main.go   

Problem:

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 bbut I want to use the local directory thing.

What am I doing wrong and what’s this error about

NOTE: I want add that I’m using windows as os

Thank you.

How to solve:

There are a few issues:

  • Packages are imported, not files (as noted in other answers)
  • File absolute import paths are not valid as the error states. An application can use file relative import paths (the path starts with “./”) or a path relative to the Go workspace. See the go command doc for info on the syntax. Import paths relative to the Go workspace are the preferred form.
  • It is idiomatic to use lowercase names for packages (and their corresponding directories). The camel case names in the question are workable, but it’s better to go with the flow.

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.

Answer:

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”.

Answer:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *