GOPATH and Go Web Server: 'go run myserver.go' - go

I'm at the point where want to organize my Go web server into packages. Currently I have everything in a few files and I simply type: 'go run server.go foo.go bar.go'
How do I organize my files so I don't need to keep adding files to the command line. I've investigated the GOPATH variable but it doesn't seem to work.
export GOPATH=$HOME/myserver
I moved my files to the src/ subdirectory.
myserver/src/server.go
myserver/src/foo.go
myserver/src/bar.go
Shouldn't 'go run' search $HOME/myserver/src for all go files?
I've tried these examples but they don't work.
go run server.go; # Doesn't work
go run src/server.go; # Doesn't work
By the way, all files are in 'package main'

This info is covered really well on golang.org
Read this about how to write Go code
And this about organizing go code
Tip: you can run go run * to run all files in a folder
Your above example should look something like this
$GOPATH=$HOME
The GOPATH should have:
$GOPATH
src/
pkg/
bin/
$GOPATH/src is where you would store your source code for each go project
$GOPATH/src/myserver would contain your myserver program
cd to $GOPATH/src/myserver and run go install and you would now have your myserver binary located at $GOPATH/bin/myserver
Add the location of your bin to your path export PATH=$PATH:$GOPATH/bin and you can run myserver to start your go program

go run will look for a file (or wildcard) in your current working directory.
If you would like to run your programs from anywhere, either use go build same as you would go run and move the binaries where appropriate or, better yet, set your $GOBIN environment variable and add it your $PATH -- then run go install * in your project directory.
It's also probably a good idea to make specific directories for projects instead just dumping it all in $GOPATH/src

Related

how to build go outside of source directory?

My go application directory structure is like this:
/app
go.mod
go.sum
main.go
When I build the app I usually cd into that directory and build.
cd app
go build
I wonder if I can build without cd in to app directory.
When I go go build /app, it prints go: go.mod file not found in current directory or any parent directory; see 'go help modules'.
See https://golang.org/ref/mod#commands-outside :
go build needs to be run from a module directory.
The simplest way is to cd into your module directory (cd /app) to run your go build command.
(there probably is some way to create a phony local go.mod file, and reference your /app module from there, but I wasn't able to devise a hack to do this)
Go now can change directory before build with the help of flag -C:
go build -C app
"The go subcommands now accept -C to change directory to before performing the command"
Source: https://tip.golang.org/doc/go1.20
(You don't need to run cd .. after this command. Shell stays in the same directory)
I'm pretty sure to build you will need to be in the app directory.
As a workaround if you are just wanting to be on the command line in a different directory and want to run the build with one command you can just chain the cd and go build commands together like this:
cd app; go build ; cd ..
This is the same amount of typing but could be in your command history just a couple presses of the up arrow away.
Note this is for bash or similar UNIX style shell. If using Windows cmd then I think it would be something like this (Not tested as I don’t have readily available access to a Windows machine right now):
cd app & go build & cd ..

"go get" command not generating the bin folder when it is run in a shell script

I have installed go package. When I go to the instance(VM) and run the command
go get github.com/linkedin/Burrow from a terminal/cmd it is downloading both "src" & "bin" folder under user home directory. But when I run the same command by setting GOPATH in a shell script, it is only downloading the "src" folder but not generating "bin" folder.
SOURCE_DIR="/opt/burrow"
export GOPATH=$SOURCE_DIR/go
go get $BURROW_REPO
Am I missing anything?
Use go install command (Compile and install packages and dependencies).
That command download src to $GOPATH and build it to $GOBIN.
GOBIN may not be set at the moment.
You can check by go env GOBIN. if its empty so you must set with export GOBIN=$(go env GOPATH)/bin
Also, for calling binary files from your terminal, you need to use go install command. This will create related bin file under GOBIN path.
There's a lot going on here.
The first point of your confusion is that go get does not download neither "src" nor "bin": Go packages are always contain only source code, and they typically does not contain the "src" directory in their file and directory hierarchies.
Instead, these directories are artefacts of the the Go toolchain.
The second point of confusion is that since Go 1.8, the Go toolchain uses a fallback value for the GOPATH environment variable if that is not set, and on Unix-like systems it defaults to the directory named "go" under the "home" directory of the user executing the go command.
If this directory is missing, the toolchain will create it.
Hence my stab at your problem is that you have some sort of permissions problem: when GOPATH is unset, "$HOME/go" is used — with whatever value $HOME expands to for the current user; when you set GOPATH by hand, something prevents creation of the "bin" directory under $GOPATH.
There's another possibility: you also set the GOBIN environment variable, which, when set, overrides the usual location used to install binaries built by go install (and go get).
You might study the output of go help environment to read more on the subject.
In either case, the most sensible path forward is to run go install with the -x command-line option and see where the command tries to put the generated executable image, and why this fails (if at all).
You might study the output of go help install and go help build to read more on the subject.
You might also consider forcing usage of Go modules for your particular case:
running GO111MODULES=on go get github.com/linkedin/Burrow would work like five times faster for your use case.
Be sure to study the output of go help modules and go help mod-get first.
bin folder or src folders are not automatically created for you by the go get command. Here are the standard steps creating a new project in go assuming this the first time you are creating a project in go:
Under your workspace directory, create a project directory, say "project1" bin, src directories.
Set GOPATH, GOBIN:
export GOPATH=~/workspace/project1/
export GOBIN=~/workspace/project1/bin
Now if you need just the source code, do a go get github.com/linkedin/Burrow
or if you need a binary do a go install github.com/linkedin/Burrow
The binary will be stored under ~/workspace/project1/bin and source code under ~/workspace/project1/
Same steps would apply either if your creating your project through a make file or terminal

Go lang environment and paths

I have few apps cloned from github, but not sure if I do everything right. I recently installed go.
$ go
Go is a tool for managing Go source code.
Usage:
go command [arguments]
The commands are:
build compile packages and dependencies
clean remove object files
doc show documentation for package or symbol
env print Go environment information
fix run go tool fix on packages
fmt run gofmt on package sources
generate generate Go files by processing source
get download and install packages and dependencies
install compile and install packages and dependencies
list list packages
run compile and run Go program
test test packages
tool run specified go tool
version print Go version
vet run go tool vet on packages
Use "go help [command]" for more information about a command.
Additional help topics:
c calling between Go and C
buildmode description of build modes
filetype file types
gopath GOPATH environment variable
environment environment variables
importpath import path syntax
packages description of package lists
testflag description of testing flags
testfunc description of testing functions
Use "go help [topic]" for more information about that topic.
And I have things configured accordingly (exported variables etc..) also added them into ~/.bashrc however I still need to change directory and go to my go/bin folder.. is this what all are doing or there is something I can change. Would be great if you can point me on some sort of docs (not go lang please!).
I am on Mac OS X.
Verify that the binary you are trying to run is in your $GOPATH/bin directory, e.g. it should appear when you run ls $GOPATH/bin
Next, verify that $GOPATH/bin is in your $PATH, e.g. it should appear with echo $PATH. If this $GOPATH/bin is not in your $PATH, add it e.g. export PATH=$GOPATH/bin:$PATH (you may want to add this to your .bashrc).
You can run go env to see your $GOPATH and some environment variable
In Mac OS X, open terminal
create a .profile file
touch .profile
edit it
vim .profile
add this to your first line
export GOPATH=$HOME/work/ or whatever directory your Go files are in
save :w and quit :q
restart terminal
change to your new GOPATH/bin directory to confirm
cd $GOPATH/bin

How to compile .go file to specific directory, or to gitignore the binaries?

Right now I'll just run go build __.go, but I'm wondering if it's possible to have that file built in a subdirectory (e.g. a /bin folder). It would just make gitignoring the binary files a lot cleaner, and right now I'm not really sure what else is a good approach as I'm also struggling to create a working gitignore exception rule that isn't just "Ignore all files, except .go files".
My current solution is naming the binary files every time I build them (e.g. go build -o hello.bin hello.go), but this seems laborious.
you can use the -o flag.
cd to the directory where you have the main.go file.
use this command - go build -o DirectoryPath
Where DirectoryPath is the location where you want to create the binary file to.
Instead of using go build *.go, you can do following:
Setup Go workspace, using this official go resource: How to write go code
Define GOBIN and GOPATH environment variable.GOBIN environment variable will point to the directory where you want to store your executables.GOPATH environment variable will point to the directory, where you've setup go workspace.
Now, instead of doing go build *.go, you can use go install {YourCodePath}, where {YourCodePath}, is relative path of your code in go workspace. And if the build is successful, you can find your executable in directory, pointed by GOBIN.

How to compile Go program consisting of multiple files?

I have a small program that consists of three files, all belonging to the same package (main). But when I do go build main.go the build doesn't succeed. When it was just one file (main.go), everything worked fine.
Now that I took some effort to separate the code, it looks like the compiler is unable to find the stuff that was taken out of main.go and put into these two other files (that reside in the same directory as the main.go). Which results in undefined 'type' errors.
How to compile this program that consists of multiple files?
New Way (Recommended):
Please take a look at this answer.
Old Way:
Supposing you're writing a program called myprog :
Put all your files in a directory like this
myproject/go/src/myprog/xxx.go
Then add myproject/go to GOPATH
And run
go install myprog
This way you'll be able to add other packages and programs in myproject/go/src if you want.
Reference : http://golang.org/doc/code.html
(this doc is always missed by newcomers, and often ill-understood at first. It should receive the greatest attention of the Go team IMO)
When you separate code from main.go into for example more.go, you simply pass that file to go build/go run/go install as well.
So if you previously ran
go build main.go
you now simply
go build main.go more.go
As further information:
go build --help
states:
If the arguments are a list of .go files,
build treats them as a list of source files specifying a single package.
Notice that go build and go install differ from go run in that the first two state to expect package names as arguments, while the latter expects go files. However, the first two will also accept go files as go install does.
If you are wondering: build will just build the packages/files, install will produce object and binary files in your GOPATH, and run will compile and run your program.
Since Go 1.11+, GOPATH is no longer recommended, the new way is using Go Modules.
Say you're writing a program called simple:
Create a directory:
mkdir simple
cd simple
Create a new module:
go mod init github.com/username/simple
# Here, the module name is: github.com/username/simple.
# You're free to choose any module name.
# It doesn't matter as long as it's unique.
# It's better to be a URL: so it can be go-gettable.
Put all your files in that directory.
Finally, run:
go run .
Alternatively, you can create an executable program by building it:
go build .
# then:
./simple # if you're on xnix
# or, just:
simple # if you're on Windows
For more information, you may read this.
Go has included support for versioned modules as proposed here since 1.11. The initial prototype vgo was announced in February 2018. In July 2018, versioned modules landed in the main Go repository.
In Go 1.14, module support is considered ready for production use, and all users are encouraged to migrate to modules from other dependency management systems.
You could also just run
go build
in your project folder myproject/go/src/myprog
Then you can just type
./myprog
to run your app
It depends on your project structure. But most straightforward is:
go build -o ./myproject ./...
then run ./myproject.
Suppose your project structure looks like this
- hello
|- main.go
then you just go to the project directory and run
go build -o ./myproject
then run ./myproject on shell.
or
# most easiest; builds and run simultaneously
go run main.go
suppose your main file is nested into a sub-directory like a cmd
- hello
|- cmd
|- main.go
then you will run
go run cmd/main.go
You can use
go build *.go
go run *.go
both will work also you may use
go build .
go run .
Yup! That's very straight forward and that's where the package strategy comes into play. there are three ways to my knowledge.
folder structure:
GOPATH/src/
github.com/
abc/
myproject/
adapter/
main.go
pkg1
pkg2
warning: adapter can contain package main only and sun directories
navigate to "adapter" folder. Run:
go build main.go
navigate to "adapter" folder. Run:
go build main.go
navigate to GOPATH/src
recognize relative path to package main, here "myproject/adapter". Run:
go build myproject/adapter
exe file will be created at the directory you are currently at.

Resources