Go run/build cannot find source files - go

I am trying to run a simple hello world style program that imports a print function from a separate custom package but Go is unable to find it despite teh correct $GOPATH etc being set.
What is missing that will make teh file be picked up?
etherk1ll#ubuntu:~/Development/GoWorkSpace/src/sonarparser$ echo $GOPATH
/home/etherk1ll/Development/GoWorkSpace/
etherk1ll#ubuntu:~/Development/GoWorkSpace/src/sonarparser$ pwd
/home/etherk1ll/Development/GoWorkSpace/src/sonarparser
etherk1ll#ubuntu:~/Development/GoWorkSpace/src/sonarparser$ ls
jsonparser.go main.go
etherk1ll#ubuntu:~/Development/GoWorkSpace/src/sonarparser$ go run main.go
main.go:5:2: cannot find package "sonarparser/jsonparser" in any of:
/usr/local/go/src/sonarparser/jsonparser (from $GOROOT)
/home/etherk1ll/Development/GoWorkSpace/src/sonarparser/jsonparser (from $GOPATH)
main.go
package main
import (
"fmt"
"jsonparser"
)
func main() {
fmt.Println("Hello world 1")
fmt.Println(jsonparser.HelloTwo)
}
jsonparser.go
package jsonparser
import "fmt"
func HelloTwo() {
fmt.Println("Hello world 2")
}

Because jsonparser.go and main.go are in the same package, Go requires those files to have the same package name. And because you defined the main function for the execution, the package must be "main".
Step 1: So you should rename jsonparser.go's package to main.
// jsonparser.go
package main
import "fmt"
func HelloTwo() {
fmt.Println("Hello world 2")
}
Step 2: You need to update main.go file to correct the import path:
// main.go
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello world 1")
HelloTwo()
}
Step 3: Then you run the following command (you must include all necessary files in the command)
go run main.go jsonparser.go

Related

How to import go file from internal folder?

I have a go project whose structure is:
- internal
- client.go
main.go
go.mod
go.mod:
module github.com/zhaoyi0113/eml-transaction
go 1.17
require github.com/go-resty/resty/v2 v2.7.0
require golang.org/x/net v0.0.0-20211029224645-99673261e6eb // indirect
client.go:
func SendTransaction() {
}
main.go
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
import "github.com/zhaoyi0113/eml-transaction/internal"
func main() {
SendTransaction()
}
The problem is that SendTransaction is invisible in main.go. When I run go build, I got below error:
./main.go:11:8: imported and not used: "github.com/zhaoyi0113/eml-transaction/internal"
./main.go:36:2: undefined: SendTransaction
./main.go:36:18: undefined: TransactionRequest
I don't understand why the import is not used. What is the right way to import it?
Just figured out how it works. I have to use internal as the prefix to call this method.
internal.SendTransaction(internal.TransactionRequest{})
``

go-run is giving me an error `cannot find package` on a relative submodule

I have the following dir structure
~/test
| lala
- lala.go
- main.go
And the contents:
main.go:
package main
import (
"fmt"
"./lala"
_ "github.com/lib/pq"
)
func main() {
fmt.Println(lala.asd)
}
lala.go:
package lala
import (
_ "github.com/lib/pq"
"github.com/gorilla/securecookie"
)
func asd() string {
return string(securecookie.GenerateRandomKey(32))
}
Then i execute:
~/test$ go mod init asdasd.com/asdasd
~/test$ go mod tidy
~/test$ go run main.go
But i get
lala/lala.go:6:2: cannot find package
That line is the one with the securecookie, which is a remote path.
I tried go mod init && go mod tidy in the lala dir but the error is the same.
Do not make use of relative paths in imports. Your import path should start with the project directory(The directory under src folder).
Change this
import "./lala"
To
import "asdasd.com/asdasd/lala"

Golang local import

I am attempting to do a local import but it fails.
My environment is:
echo $GOPATH
/home/peter/go
echo $GOROOT
/usr/local/go
The entry point is:
/home/peter/go/src/projects/pkgs1/main.go
The imported file is:
/home/peter/go/src/projects/pkgs2/stuff.go
main.go
package main
import (
"fmt"
"projects/pkgs2" // <- this does not resolve
)
func main(){
fmt.Println("123")
pkgs2.X()
}
stuff.go
package pkgs2
import "fmt"
func X(){
fmt.Println("X")
}
Any pointers on what I do wrong?
Your import path is correct and should resolve successfully, but as written, your program won't compile because the import isn't being used and there is no local function named x.
As mentioned by mkopriva your x function in pkgs2 isn't exported and you have not qualified it when trying to use it in your main package.
To export a function, it needs to start with a capital letter.
To use the function in another package, you need to prefix the package name to the function name.
main.go
package main
import (
"fmt"
"projects/pkgs2"
)
func main(){
fmt.Println("123")
pkgs2.X()
}
stuff.go
package pkgs2
import "fmt"
func X(){
fmt.Println("X")
}

My main.go file cannot see other files

I need some help understanding what is wrong with my file layout in a simple web application.
$GOPATH/src/example.com/myweb
I then have 2 files:
$GOPATH/src/example.com/myweb/main.go
$GOPATH/src/example.com/myweb/api.go
Both files have:
package main
The api.go file looks like:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type API struct {
URI string
Token string
Secret string
client *http.Client
}
...
My main.go file looks like:
package main
import (
"github.com/gorilla/mux"
"html/template"
"net/http"
)
var (
templates = template.Must(template.ParseFiles("views/home.html", "views/history.html", "views/incident.html"))
api = API{
URI: "http://localhost:3000",
Token: "abc",
Secret: "123",
}
)
func renderTemplate(w http.ResponseWriter, tmpl string, hp *HomePage) {
..
..
}
func WelcomeHandler(w http.ResponseWriter, r *http.Request) {
..
..
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", WelcomeHandler)
r.PathPrefix("/assets/").Handler(
http.StripPrefix("/assets/", http.FileServer(http.Dir("assets/"))))
http.ListenAndServe(":9000", r)
}
In the code I excluded, I basically use structs that are defined in my api.go file, and I get this error when doing:
go run main.go
# command-line-arguments
./main.go:16: undefined: API
./main.go:23: undefined: User
What exactly am I doing wrong here?
I tried changing the package name in api.go to myweb but that didn't help.
Am I suppose to use the package name myweb? Is just 1 file suppose to have main?
You're compiling only the main.go file. You should use:
go run main.go api.go
Or:
go run *.go
If you're writing a complex application, you might add everything to packages in subdirectories and have a single main.go file. For instance, etcd has an etcdmain subdirectory/package along with other subdirectories/packages. Something like:
/alarm
/auth
/cmd
/etcdmain
...
And the main.go file is simply:
package main
import "github.com/coreos/etcd/etcdmain"
func main() {
etcdmain.Main()
}
You are using golang workspace project, which is good for the structure for your application and it also standardize.
When we use the golang workspace, you can not run single go file. You need to call go build / go install.
Install
go install example.com/myweb
The command above will compile your main package on example.com/myweb. And the myweb executable binary will be placed on the GOPATH/bin. And you can run it manually.
Build
go build example.com/myweb
The command is similar to go install but the binary executable file will be placed on the current directory when you call the command, instead of on GOPATH/bin (unless your current directory is GOPATH/bin).
For more information please check this link.

Call a function from another package in Go

I have two files main.go which is under package main, and another file with some functions in the package called functions.
My question is: How can I call a function from package main?
File 1: main.go (located in MyProj/main.go)
package main
import "fmt"
import "functions" // I dont have problem creating the reference here
func main(){
c:= functions.getValue() // <---- this is I want to do
}
File 2: functions.go (located in MyProj/functions/functions.go)
package functions
func getValue() string{
return "Hello from this another package"
}
You import the package by its import path, and reference all its exported symbols (those starting with a capital letter) through the package name, like so:
import "MyProj/functions"
functions.GetValue()
You should prefix your import in main.go with: MyProj, because, the directory the code resides in is a package name by default in Go whether you're calling it main or not. It will be named as MyProj.
package main just denotes that this file has an executable command which contains func main(). Then, you can run this code as: go run main.go. See here for more info.
You should rename your func getValue() in functions package to func GetValue(), because, only that way the func will be visible to other packages. See here for more info.
File 1: main.go (located in MyProj/main.go)
package main
import (
"fmt"
"MyProj/functions"
)
func main(){
fmt.Println(functions.GetValue())
}
File 2: functions.go (located in MyProj/functions/functions.go)
package functions
// `getValue` should be `GetValue` to be exposed to other packages.
// It should start with a capital letter.
func GetValue() string{
return "Hello from this another package"
}
Export function getValue by making 1st character of function name capital, GetValue
you can write
import(
functions "./functions"
)
func main(){
c:= functions.getValue() <-
}
If you write in gopath write this import functions "MyProj/functions" or if you are working with Docker
In Go packages, all identifiers will be exported to other packages if the first letter of the identifier name starts with an uppercase letter.
=> change getValue() to GetValue()
you need to create a go.mod file in the root directory of your project: go mod init module_name
the name of exposed function should start with capital letter
import(
"module_name/functions"
)
func main(){
functions.SomeFunction()
}

Resources