Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import files from current directory in go

Tags:

import

path

go

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

like image 522
WillYum Avatar asked Oct 18 '25 14:10

WillYum


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!