Reputation: 174
I am creating a web API.
I built my server and controller in the same file main.go
.
I created another file name model.go
where I declare a Person
struct.
I can't export my model in main.go
.
Every time I run or build I get this error :
can't load package: package .: found packages main
Is there a way to export func/const and import them in file with good path? (Like the way JavaScript works).
This is my tree:
myapp/
--main.go/
--model.go/
This is my import: main.go
package main
import (
"encoding/json"
"log"
"net/http"
"./person"
"github.com/gorilla/mux"
)
model.go
package person
type Person struct {
ID string `json:"id,omitempty"`
Firstname string `json:"firstname,omitempty"`
Lastname string `json:"lastname,omitempty"`
Address *Address `json:"address,omitempty"`
}
var people []Person
Upvotes: 4
Views: 9526
Reputation:
within the same folder you must have the same package name.
When golang processes imports it loads all files under the same directory as a whole.
given the code you presented, model.go package name must be main.
You simply don t need to import model.go from main.go.
Now, there s a little thing to know about. When you will run go build/run/install, it will take the list of files passed as parameters to initialize the build process.
In your current setup that means you must pass all files composing the main package to the command line, otherwise, they will be ignored, in your case that means a build failure.
In plain text, you will do go build *.go
instead of go build main.go
In the future if you want to avoid multiple source files to build, you should have a unique main.go, with the minimum code in it to initialize the program you are writing. As a consequence the content of model.go
will exist within a different package (directory), and will be imported into main via an import xyz
statement.
Finally, import path of the import
directives must not be relative to the current working directory. They are all GOPATH/src
based.
Upvotes: 7