Building package structure with child-/sub-packages - go

I'm trying to make a simple calculator in Go. I'm designing it in such a way that I can build a command-line interface first and easily swap in a GUI interface. The project location is $GOPATH/src/gocalc (all paths hereafter are relative to the project location). The command-line interface logic is stored in a file gocalc.go. The calculator logic is stored in files calcfns/calcfns.go and operations/operations.go. All files have package names identical to their filename (sans extension) except the main program, gocalc.go, which is in the package main
calcfns.go imports operations.go via import "gocalc/operations"; gocalc.go imports calcfns.go via import "gocalc/calcfns"
To summarize:
$GOPATH/src/gocalc/
gocalc.go
package main
import "gocalc/calcfns"
calcfns/
calcfns.go
package calcfns
import "gocalc/operations"
operations/
operations.go
package operations
When I try to go build operations (from the project dir), I get the response: can't load package: package operations: import "operations": cannot find package
When I try go build gocalc/operations, I get can't load package: package gocalc/operations: import "gocalc/operations": cannot find package
When I try go build operations/operations.go, it compiles fine
When I try to go build calcfns or go build gocalc/calcfns, I get can't load package... messages, similar to those in operations; however, when I try to build calcfns/calcfns.go it chokes on the import statement: import "gocalc/operations": cannot find package
Finally, when I try go build . from the project dir, it chokes similar to the previous paragraph: import "gocalc/calcfns": cannot find package
How should I structure my child packages and/or import statements in such a way that go build won't fail?

Stupidly, I forgot to export my GOPATH variable, so go env displayed "" for GOPATH. (thanks to jnml for suggesting to print go env; +1).
After doing this (and moving the main program to its own folder {project-dir}/gocalc/gocalc.go), I could build/install the program via go install gocalc/gocalc.
Moral of the story, make sure you type export GOPATH=... instead of just GOPATH=... when setting your $GOPATH environment variable

Please try to also add output of $ go env to provide more clues. Otherwise both the directories structure and (the shown) import statements looks OK.
However the sentence
When I try to go build operations (from the project dir), I get the response: can't load package: package operations: import "operations": cannot find package
sounds strange. It seems to suggest you have
package operations
import "operations"
in 'operations.go', which would be the culprit then...?

Very easy:
Lets say I have a project/app named: golang-playground
Put your root dir under GOPATH/src/, in my case GOPATH=~/go/src (run command go env to get your GOPATH). so complete path for my app is ~/go/src/golang-playground
Lets say you want to use function Index() inside of file: router.go from my main.go file (which of course is on root dir). so in main.go:
import (
...
"golang-playground/router"
)
func main() {
foo.Bar("/", router.Index) // Notice caps means its public outside of file
}

Related

Project structure and importing packages

I'm just starting to learn Go and I'm wondering how to best organize my project and import packages. I created a project at $GOPATH/src/my_project. It contains the file main.go and the folder foo containing the file bar.go.
$GOPATH/src/my_project
main.go
foo/
bar.go
My main.go looks as follows
package main
import (
"./foo"
"fmt"
)
func main() {
fmt.Println("Main")
foo.Baz()
}
Here is the foo.go
package foo
import "fmt"
func Baz() {
fmt.Println("Baz")
}
It works the way I expect it to, but I wonder if this is really the right way to structure a project and import packages, because most tutorials only import packages from github and never from local.
Thanks for your answers..
Relative imports are possible in Go but they are not encouraged to be used.
Instead you always use the full path of the package. In your case that would be my_project/foo. This is is relative to the GOPATH/src folder.
However, since we have Go modules now which make things a tiny bit more complicated to start with but have a lot of advantages in the long run.
Just earlier today I gave a step by step guide on how to set up a new project with Go modules: After go install the import doesn't recognize the package
The module name in this guide is the basis for your project then and all paths in the module build on that path. Let me give an example:
Let's say you name your module github.com/yourName/myProject. Then you can import the subpackage foo with github.com/yourName/myProject/foo.
Note: The module path should be the same as the git URL, that way you can just get the module with go get. If you don't plan on ever uploading the project to github or another git URL, you should still choose a unique name. Starting with a domain you own is a good idea -- for uniqueness.

How to include my `log` package instead of built-in `log` package in `golang`?

I have an log package in my project src folder. But when I include the log package from an another package as following, the go seams find the log in the system folder instead of my package.
import ("log")
And seams I cannot using relative path to import log package, because go install give following error:
local import "./log" in non-local package
So how can I let the go using my log package?
You need to add your package inside $GOPATH
So if your package is in
$GOPATH/src/github.com/ZijingWu/awesomeapp/src/
your log package would be in
$GOPATH/src/github.com/ZijingWu/awesomeapp/src/log
then it would be possible to use
import("github.com/ZijingWu/awesomeapp/src/log")
The paths seams a bit strange tho, and maybe you should consider adding the log package as a completely separate repository on github, so it would look something like.
import("github.com/ZijingWu/log")
Just using github as an example here, could of course be placed wherever, also just guessing at your username there. Doesnt need to be in github either you can just place it localy on your computer in the $GOPATH, but then noone else would be able to build your package.

Accessing local packages within a go module (go 1.11)

I'm trying out Go's new modules system and am having trouble accessing local packages. The following project is in a folder on my desktop outside my gopath.
My project structure looks like:
/
- /platform
- platform.go
- main.go
- go.mod
// platform.go
package platform
import "fmt"
func Print() {
fmt.Println("Hi")
}
// main.go
package main
import "platform"
func main() {
platform.Print()
}
go build main.go tells me
cannot find module for path platform
Let me define this first modules are collections of packages. In Go 11, I use go modules like the following:
If both packages are in the same project, you could just do the following:
In go.mod:
module github.com/userName/moduleName
and inside your main.go
import "github.com/userName/moduleName/platform"
However, if they are separate modules, i.e different physical paths and you still want to import local packages without publishing this remotely to github for example, you could achieve this by using replace directive.
Given the module name github.com/otherModule and platform, as you've called it, is the only package inside there. In your main module's go.mod add the following lines:
module github.com/userName/mainModule
require "github.com/userName/otherModule" v0.0.0
replace "github.com/userName/otherModule" v0.0.0 => "local physical path to the otherModule"
Note: The path should point to the root directory of the module, and can be absolute or relative.
Inside main.go, to import a specific package like platform from otherModule:
import "github.com/userName/otherModule/platform"
Here's a gentle introduction to Golang Modules
I would strongly suggest you to use go toolchain which takes care of these issues out of the box. Visual Studio Code with vscode-go plugin is really useful.
Problem here is that Go requires relative paths with respect to your $GOPATH/src or module in import statement. Depending on where you are in your GOPATH, import path should include that as well. In this case, import statement must include go module path in go.mod
GOPATH
Assume your project resides here:
$GOPATH/src/github.com/myuser/myproject
Your import path should be:
import "github.com/myuser/myproject/platform"
VGO
Assume your go.mod file is:
module example.com/myuser/myproject
Your import path should be:
import "example.com/myuser/myproject/platform"
As someone new to go I didn't immediately understand the accepted answer – which is great, by the way. Here's a shorter answer for those very new people!
In go modules/packages are expressed as urls that you import in your code:
import your.org/internal/fancy_module
But wait! My code isn't at a url, what's happening??
This is the cleverness of go. You pretend there's a url even when there isn't one. Because:
This makes including easier as no matter where your file is located the import uses the same url (the code stays the same even if the files move!)
You can have packages that having naming conflicts. So google.com/go-api/user doesn't conflict with the definitions at your.org/internal/user
Someday you might publish a url on GitHub and all the code will just work
That's all great Evan, but how do I import a relative path?
Good question! You can import by changing your go.mod file to have this line:
module fancy_module
go 1.16
replace your.org/fancy_module => ../path/to/fancy_module
Given the Golang Project structure
/
- /platform
- platform.go
- main.go
- go.mod
To access the methods or structs...etc (which are public) from local packages of /platform is simple, shown below
// main.go
package main
import (
p "./platform"
)
func main() {
p.Print()
}
this should work

how can i use a function inside main package from a file in another package in GO?

Hi I want to call a method inside the main package, my project struct is like this:
src:
go files : package main
Postgres folder:
go files: postgres package
now I want to call a method inside main package from the go files inside the postgres folder that is from postgres package.
I tried to import "foo/src"
then using src.Myfunction but I got an error:
import "foo/src" is a program, not an importable package
The package main is supposed to be used only to implement the binary/command specific code. It usually imports code from other packages to glue everything together. If you need to import something from the package main, that code is probably not specific to that command, so it should belong to another package. After you refactor the code, you can import it from the package main and from your other package which also requires it.

How to make go build work with nested directories

In the process of learning go I was playing around with making my own libraries. Here is what I did: in my $GOPATH/src I have two folders: mylibs and test. The test folder has a file called test.go which contains
package test
import "mylibs/hi/saysHi"
func main() {
saysHi.SayHi()
}
The mylibs folder contains another folder called hi, which has a file called saysHi.go containing:
package saysHi
import "fmt"
func SayHi() {
fmt.Printf("Hi\n")
}
So the directory structure looks like this:
GOPATH/src
test
test.go
mylibs
hi
saysHi.go
The problem is that when I try to compile test it complains saying
cannot find package "mylibs/hi/saysHi" in any of:
[...]
$GOPATH/src/mylibs/hi/saysHi (from $GOPATH)
I have deliberately made the directory structure deeper than necessary. If I make a simpler directory structure where I place saysHi.go in $GOPATH/saysHi/saysHi.go then it works.
But I don't see a reason for why this wouldn't work. Any ideas?
Generally speaking, your directory name should match the package name. So if you define
package saysHi
and want to import it with
import "mylibs/hi/saysHi"
you should place it in a structure like this:
mylibs
hi
saysHi
saysHi.go
The name of the .go file(s) inside the package makes no difference to the import path, so you could call the .go file anything you like.
To explain it a bit further, the import path you use should be the name of the directory containing the package. But, if you define a different package name inside that directory, you should use that name to access the package inside the code. This can be confusing, so it's best to avoid it until you understand where it's best used (hint: package versioning).
It gets confusing, so for example, if you had your package in the path
mylibs
hi
saysHi.go
And inside saysHi.go defined,
package saysHi
Then in test.go you will import it with
import "mylibs/hi"
And use it with
saysHi.SayHi()
Notice how you import it with the final directory being hi, but use it with the name saysHi.
Final note
Just in case you didn't know the following: your test file is called test.go, and that's fine, if it's just as an example, and not an actual test file for saysHi.go. But if it is/were a file containing tests for saysHi.go, then the accepted Go standard is to name the file saysHi_test.go and place it inside the same package alongside saysHi.go.
One more final note
I mentioned how you are allowed to choose a different package name from the directory name. But there is actually a way to write the code so that it's less confusing:
import (
saysHi "mylibs/hi"
)
Would import it from the mylibs/hi directory, and make a note of the fact that it should be used with saysHi, so readers of your code understand that without having to go look at the mylibs/hi code.

Resources