6

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.

user3087000
  • 731
  • 1
  • 13
  • 24

2 Answers2

5

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.

JimB
  • 104,193
  • 13
  • 262
  • 255
  • Thank you. So if you have any better solution to this problem? – user3087000 Jan 15 '16 at 16:41
  • @user3087000: yes, don't use relative imports, and structure your code as described in the docs: [How to Write Go Code](https://golang.org/doc/code.html) – JimB Jan 15 '16 at 16:43
  • But like the code I posted in the content, I need a way to organize my models. How can I achieve the same goal but not use the relative path? – user3087000 Jan 15 '16 at 16:48
  • @user3087000: Use the full import path, which is rooted at `$GOPATH/src/`, e.g. `project/models`. Please read through the document I linked, which provides many examples. – JimB Jan 15 '16 at 16:58
-1

As you are using "github.com/gin-gonic/gin" in your code. It is an external import. So go compiler will try to find this package in your workspace. So you need manually download those package in your go workspace or build path "go get github.com/gin-gonic/gin".