Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang - Why can't I import local package in GOPATH/src/project but can in home directory?

Tags:

go

I have a project, its folder structure is like following:

    /project
        models/
            Product.go
        main.go

The content of main.go is:

package main

import (
    "./models"
    "fmt"
    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    fmt.Println(models.Product{})
    r.GET("/", func(c *gin.Context) {
        c.String(200, "he")
    })

    r.Run(":3000")
}

The content of Product.go is:

package models

type Product struct {
    Name string
}

What I get from typing go env is:

GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/Mac/go"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.5.3/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.5.3/libexec/pkg/tool/darwin_amd64"
GO15VENDOREXPERIMENT=""
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -    fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1"

When the location of the project directory is $GOPATH/src/project, If I run go run main.go, what I get is this error message: ./main.go:: can't find import: "github.com/gin-gonic/gin".

But when the location of project directory is ~/project, go run main.go can work as expected.

I use go1.5.3.

Can anyone help me. Thanks.

like image 384
user3087000 Avatar asked Jan 15 '16 16:01

user3087000


People also ask

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.

Is Gopath still needed?

They are not necessary and mixing GOPATH configurations with Go Modules is a way of causing confusion. More specifically: The default value for the GOPATH (when not set) is ~/go , so when I mention the directory ~/go I mean the default directory used by Go.


1 Answers

Relative import paths are only allowed as a convenience, mostly for experimentation. They are not fully supported by go build and go install. If you want your package to work with the go tools, don't use relative imports. Structure your code as described in How to Write Go Code.

like image 53
JimB Avatar answered Oct 31 '22 08:10

JimB