Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import local packages when using Go modules

Tags:

go

I wish to create a large project, so I need to create some kind of folder structure. I am quite new to Go, but, as I understand, the way to do it is to create packages, right? I am using Go modules, I have tried many different solutions found here and on Google, but none of them seem to work for me.

All I want to for now, is import exported function from example.go file into main.go

Folder structure is as follows:

client
example
---example.go
go.mod
go.sum
main.go
  1. I have created module file with go mod init, see the first code snippet below
  2. Second code snippet shows how the header of main.go looks like
  3. Third snippet is the package with the function I want to import
    module exampleapp
    go 1.12
    require (
        github.com/gin-gonic/contrib v0.0.0-20190408155029-b5986969cb50
        github.com/gin-gonic/gin v1.4.0
    )

package main
import (
    "net/http"
    "exampleapp/example"
)
    package example
    import (
        "net/http"
        "github.com/gin-gonic/gin"
    )

    func GetAllEmployees(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "pong",
        })
    }

For the most part, when I try to add package in main.go, VSCode automatically removes the line and in the main function says that GetAllEmployees is not defined. I managed to catch error package before the package is removed, it says -

"imported and not used: "exampleapp/example"
Am I wrong to use "exampleapp/example" module name exampleapp here? I tried without the exampleapp and "./example/example", but then I get an error that says it cannot find module for path.

Help would be highly appreciated, as I have been stuck on this for quite some time and can't figure out, what am I missing here.

like image 203
Rivao Avatar asked May 19 '19 16:05

Rivao


People also ask

What is the difference between Go module and package?

In Go, a package is a directory of .go files, and packages form the basic building blocks of a Go program. Using packages, you organize your code into reusable units. A module, on the other hand, is a collection of Go packages, with dependencies and versioning built-in.

Can I import package main in Golang?

You cannot import the main package. Any shared code should go in a separate package, which can be imported by main (and other packages).

Which one is the correct way to import multiple packages libraries in Golang?

Both single and multiple packages can be imported one by one using the import keyword.


1 Answers

It should be like that (main.go):

package main
import (
    "exampleapp/example"
)

func main() {
    example.GetAllEmployees(...)
}
like image 115
Sergey Narozhnyy Avatar answered Oct 23 '22 03:10

Sergey Narozhnyy