Search code examples
gogo-gin

GoLang custom package import issue


I'm learning GoLang, and got into an issue.

I created the mod file with go mod init main

Next I created controller and Routes folder which looks something like below:

├── contollers
│   └── users.controller.go
├── routes
│   ├── index.go
│   └── users.routes.go
├── vendor
│   └── modules.txt
├── go.mod
├── go.sum
└── main.go

in the mod file the module looks like something like this module main

Now when I'm trying to import controller into router, it's giving me import error.

I been doing below things. Attempt - 1

import (
    "$GOPATH/controllers"

    "github.com/gin-gonic/gin"
)

it's giving invalid import path: "$GOPATH/controllers"syntax error

Attempt - 2

import (
    "$GOPATH/main/controllers"

    "github.com/gin-gonic/gin"
)

again the error is same

Attempt - 3

import (
    "main/controllers"

    "github.com/gin-gonic/gin"
)

controller.go

package controllers;

import (
    "fmt"

    "github.com/gin-gonic/gin"
)

func HealthCheck() gin.HandlerFunc {
    return func (c *gin.Context)  {
        fmt.Println("reached controller")
    }
}

router.go

package routes

import (
    "bootcamp.com/server/controllers"

    "github.com/gin-gonic/gin"
)

func UserRouters(inComingRoutes *gin.Engine) {
    inComingRoutes.GET("/api/health", controllers.HealthCheck());
}

it's throwing error like this, could not import main/controllers (no required module provides package "main/controllers")

I been stuck with this for 3-4 hours, can anyone please suggest me how can I import that controller into my route.

Thanks in advance.


Solution

    1. Modify the module path by editing go.mod:
    - module main
    + module example.com/hello
    
    1. Modify the import path:
      import (
    -     "main/controllers"
    +     "example.com/hello/controllers"
    
          "github.com/gin-gonic/gin"
      )
    
    1. controller.go (remove trailing ;):
    - package controllers;
    + package controllers
    
    1. rename the directory contollers to controllers to match the package name (r is missed).

    2. remove the vendor folder.

    Explanation:

    1. main has a special meaning in go. Quotes from the golang spec:

    A complete program is created by linking a single, unimported package called the main package with all the packages it imports, transitively. The main package must have package name main and declare a function main that takes no arguments and returns no value.

    1. Import paths without dots are reserved for the standard library and go toolchain. See cmd/go: document that module names without dots are reserved.