How to call function from another file in Go - go

I want to call function from another file in Go. Can any one help?
test1.go
package main
func main() {
demo()
}
test2.go
package main
import "fmt"
func main() {
}
func demo() {
fmt.Println("HI")
}
How to call demo in test2 from test1?

You can't have more than one main in your package.
More generally, you can't have more than one function with a given name in a package.
Remove the main in test2.go and compile the application. The demo function will be visible from test1.go.

Go Lang by default builds/runs only the mentioned file. To Link all files you need to specify the name of all files while running.
Run either of below two commands:
$go run test1.go test2.go. //order of file doesn't matter
$go run *.go
You should do similar thing, if you want to build them.

I was looking for the same thing. To answer your question "How to call demo in test2 from test1?", here is the way I did it. Run this code with go run test1.go command. Change the current_folder to folder where test1.go is.
test1.go
package main
import (
L "./lib"
)
func main() {
L.Demo()
}
lib\test2.go
Put test2.go file in subfolder lib
package lib
import "fmt"
// This func must be Exported, Capitalized, and comment added.
func Demo() {
fmt.Println("HI")
}

A functional, objective, simple quick example:
main.go
package main
import "pathToProject/controllers"
func main() {
controllers.Test()
}
control.go
package controllers
func Test() {
// Do Something
}
Don't ever forget: Visible External Functions, Variables and Methods starts with Capital Letter.
i.e:
func test() {
// I am not Visible outside the file
}
func Test() {
// I am VISIBLE OUTSIDE the FILE
}

If you just run go run test1.go and that file has a reference to a function in another file within the same package, it will error because you didn't tell Go to run the whole package, you told it to only run that one file.
You can tell go to run as a whole package by grouping the files as a package in the run commaned in several ways. Here are some examples (if your terminal is in the directory of your package):
go run ./
OR
go run test1.go test2.go
OR
go run *.go
You can expect the same behavior using the build command, and after running the executable created will run as a grouped package, where the files know about eachothers functions, etc. Example:
go build ./
OR
go build test1.go test2.go
OR
go build *.go
And then afterward simply calling the executable from the command line will give you a similar output to using the run command when you ran all the files together as a whole package. Ex:
./test1
Or whatever your executable filename happens to be called when it was created.

Folder Structure
duplicate
|
|--duplicate_main.go
|
|--countLines.go
|
|--abc.txt
duplicate_main.go
package main
import (
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts)
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
continue
}
countLines(f, counts)
f.Close()
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
countLines.go
package main
import (
"bufio"
"os"
)
func countLines(f *os.File, counts map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
}
go run ch1_dup2.go countLines.go abc.txt
go run *.go abc.txt
go build ./
go build ch1_dup2.go countLines.go
go build *.go

You can import functions from another file by declaring the other file as a module. Keep both the files in the same project folder.
The first file test1.go should look like this:
package main
func main() {
demo()
}
From the second file remove the main function because only one main function can exist in a package. The second file, test2.go should look like below:
package main
import "fmt"
func demo() {
fmt.Println("HI")
}
Now from any terminal with the project directory set as the working directory run the command:
go mod init myproject.
This would create a file called go.mod in the project directory. The contents of this mod file might look like the below:
module myproject
go 1.16
Now from the terminal simply run the command go run .! The demo function would be executed from the first file as desired !!

as a stupid person who didn't find out what is going on with go module
should say :
create your main.go
in the same directory write this in your terminal
go mod init "your module name"
create a new directory and go inside it
create a new .go file and write the directory's name as package name
write any function you want ; just notice your function must starts with capital letter
back to main.go and
import "your module name / the name of your new directory"
finally what you need is writing the name of package and your function name after it
"the name of your new dirctory" + . + YourFunction()
and write this in terminal
go run .
you can write go run main.go instead.
sometimes you don't want to create a directory and want to create new .go file in the same directory, in this situation you need to be aware of, it doesn't matter to start your function with capital letter or not and you should run all .go files
go run *.go
because
go run main.go
doesn't work.

Let me try.
Firstly
at the root directory, you can run go mod init mymodule (note: mymodule is just an example name, changes it to what you use)
and maybe you need to run go mod tidy after that.
Folder structure will be like this
.
├── go.mod
├── calculator
│ └── calculator.go
└── main.go
for ./calculator/calculator.go
package calculator
func Sum(a, b int) int {
return a + b
}
Secondly
you can import calculator package and used function Sum (note that function will have Capitalize naming) in main.go like this
for ./main.go
package main
import (
"fmt"
"mymodule/calculator"
)
func main() {
result := calculator.Sum(1, 2)
fmt.Println(result)
}
After that
you can run this command at root directory.
go run main.go
Result will return 3 at console.
Bonus: for ./go.mod
module mymodule
go 1.19
ps. This is my first answer ever. I hope this help.

Related

Go: import package from the same module in the same local directory

I want to create new package mycompany that will be published on Github at github.com/mycompany/mycompany-go (something similar to stripe-go or chargebee-go for example).
So I have created a folder ~/Desktop/mycompany-go on my MacOS. Then inside that folder I run go mod init github.com/mycompany/mycompany-go.
I have only these files in that local folder:
// go.mod
module github.com/mycompany/mycompany-go
go 1.19
// something.go
package mycompany
type Something struct {
Title string
}
// main.go
package main
import (
"github.com/mycompany/mycompany-go/mycompany"
)
func main() {
s := mycompany.Something {
Title: "Example",
}
}
However I get this error:
$ go run main.go
main.go:4:3: no required module provides package github.com/mycompany/mycompany-go/mycompany; to add it:
go get github.com/mycompany/mycompany-go/mycompany
I think that this is a wrong suggestion, because I need to use the local version, in the local folder, not get a remote version.
Basically I need to import a local package, from the same folder, from the same module.
What should I do? What's wrong with the above code?
You can't mix multiple packages in the same folder.
If you create a folder mycompany and put something.go inside it, that should fix the problem
The Go tool assumes one package per directory. Declare the package as main in something.go.
-- main.go --
package main
import "fmt"
func main() {
s := Something{
Title: "Example",
}
fmt.Println(s)
}
-- go.mod --
module github.com/mycompany/mycompany-go
go 1.19
-- something.go --
package main
type Something struct {
Title string
}
Runnable example: https://go.dev/play/p/kGBd5etzemK

Get Name of Current Module in Go

I am attempting to create named loggers automatically for HTTP handlers that I'm writing, where I am passed a function (pointer).
I'm using the code mentioned in this question to get the name of a function:
package utils
import (
"reflect"
"runtime"
)
func GetFunctionName(fn interface{}) string {
value := reflect.ValueOf(fn)
ptr := value.Pointer()
ffp := runtime.FuncForPC(ptr)
return ffp.Name()
}
I'm using this in my main function to try it out like so:
package main
import (
"github.com/naftulikay/golang-webapp/experiments/functionname/long"
"github.com/naftulikay/golang-webapp/experiments/functionname/long/nested/path"
"github.com/naftulikay/golang-webapp/experiments/functionname/utils"
"log"
)
type Empty struct{}
func main() {
a := long.HandlerA
b := path.HandlerB
c := path.HandlerC
log.Printf("long.HandlerA: %s", utils.GetFunctionName(a))
log.Printf("long.nested.path.HandlerB: %s", utils.GetFunctionName(b))
log.Printf("long.nested.path.HandlerC: %s", utils.GetFunctionName(c))
}
I see output like this:
github.com/naftulikay/golang-webapp/experiments/functionname/long.HandlerA
This is okay but I'd like an output such as long.HandlerA, long.nested.path.HandlerB, etc.
If I could get the Go module name (github.com/naftulikay/golang-webapp/experiments/functionname), I can then use strings.Replace to remove the module name to arrive at long/nested/path.HandlerB, then strings.Replace to replace / with . to finally get to my desired value, which is long.nested.path.HandlerB.
The first question is: can I do better than runtime.FuncForPC(reflect.ValueOf(fn).Pointer()) for getting the qualified path to a function?
If the answer is no, is there a way to get the current Go module name using runtime or reflect so that I can transform the output of runtime.FuncForPC into what I need?
Once again, I'm getting values like:
github.com/naftulikay/golang-webapp/experiments/functionname/long.HandlerA
github.com/naftulikay/golang-webapp/experiments/functionname/long/nested/path.HandlerB
github.com/naftulikay/golang-webapp/experiments/functionname/long/nested/path.HandlerC
And I'd like to get values like:
long.HandlerA
long.nested.path.HandlerB
long.nested.path.HandlerC
EDIT: It appears that Go does not have a runtime representation of modules, and that's okay, if I can do it at compile time that would be fine too. I've seen the codegen documentation and I'm having a hard time figuring out how to write my own custom codegen that can be used from go generate.
The module info is included in the executable binary, and can be acquired using the debug.ReadBuildInfo() function (the only requirement is that the executable must be built using module support, but this is the default in the current version, and likely the only in future versions).
BuildInfo.Path is the current module's path.
Let's say you have the following go.mod file:
module example.com/foo
Example reading the build info:
bi, ok := debug.ReadBuildInfo()
if !ok {
log.Printf("Failed to read build info")
return
}
fmt.Println(bi.Main.Path)
// or
fmt.Println(bi.Path)
This will output (try it on the Go Playground):
example.com/foo
example.com/foo
See related: Golang - How to display modules version from inside of code
If your goal is to just have the name of the module available in your program, and if you are okay with setting this value at link time, then you may use the -ldflags build option.
You can get the name of the module with go list -m from within the module directory.
You can place everything in a Makefile or in a shell script:
MOD_NAME=$(go list -m)
go build -ldflags="-X 'main.MODNAME=$MOD_NAME'" -o main ./...
With main.go looking like:
package main
import "fmt"
var MODNAME string
func main() {
fmt.Println(MODNAME) // example.com
}
With the mentioned "golang.org/x/mod/modfile" package, an example might look like:
package main
import (
"fmt"
"golang.org/x/mod/modfile"
_ "embed"
)
//go:embed go.mod
var gomod []byte
func main() {
f, err := modfile.Parse("go.mod", gomod, nil)
if err != nil {
panic(err)
}
fmt.Println(f.Module.Mod.Path) // example.com
}
However embedding the entire go.mod file in your use case seems overkill. Of course you could also open the file at runtime, but that means you have to deploy go.mod along with your executable. Setting the module name with -ldflags is more straightforward IMO.

GOSwagger implementation for imported packages

I'm created a project structure like,
main.go and foo/bar.go
In main.go, imported foo package and used as foo.functionName(). Now i need to write swagger document in bar.go. When i did, ended with the following error message,
unable to determine package for /PATH_TO_PROJECT/foo/bar.go
Ensure in foo/bar.go the package declared is package foo. Then the function you want to access in the main.go file should start with a capital letter. i.e.
foo/bar.go
package foo
// PrintBar with extra txt
func PrintBar(txt string) string {
return "bar with txt " + txt
}
Then in main.go
package main
import (
"fmt"
"github.com/username/project/foo"
)
func main() {
fmt.Println("in main.go")
fmt.Println(foo.PrintBar("from main.go"))
}
Try enabling Debug mode for swagger by adding DEBUG=1 in front of your swagger command. This should print you what are the paths considered.
If you look at the source code where this error is thrown, you will see this error only happens when file is not in the $GOPATH. Double check that you have the program under $GOPATH/src.

Go public struct in another file

I'm very new with GO and don't understand some basics - so I'm really don't know how to ask ask google about it. So
I have a project with 2 files, both in package main - the root of src. One file is main.go
package main
var (
node * NodeDTO
)
func main() {
node = &NodeDTO{ID: 1}
}
And another is dto.go with
package main
type NodeDTO struct {
ID int
}
So main.go tells me - "undefined: NodeDTO".
But if I create a dir dto near of main.go and use my NodeDTO from there like
package main
import "another_tcp_server/dto"
var (
node * dto.NodeDTO
)
func main() {
node = &dto.NodeDTO{ID: 1}
}
It's ok. Please tell me why this happen?
You appear to have:
$ ls
dto.go main.go
$ cat main.go
package main
var (
node * NodeDTO
)
func main() {
node = &NodeDTO{ID: 1}
}
$ cat dto.go
package main
type NodeDTO struct {
ID int
}
$
and you appear to run:
$ go run main.go
# command-line-arguments
./main.go:4:12: undefined: NodeDTO
./main.go:8:13: undefined: NodeDTO
$
The help for go run says, amongst other things:
$ go help run
usage: go run [build flags] [-exec xprog] package [arguments...]
Run compiles and runs the named main Go package.
Typically the package is specified as a list of .go source files,
but it may also be an import path, file system path, or pattern
matching a single known package, as in 'go run .' or 'go run my/cmd'.
You used a list of .go source files: go run main.go. You listed one file. You have two files: main.go and dto.go.
Use a complete list of .go source files:
$ go run main.go dto.go
$

Undefined Variables Within a Package During Build

I have two files within one package named db, one of which has a few unexported variables defined. Another one is a test file and would need to use these variables like so:
(This is the structure of the project)
$GOPATH/src/gitlab.com/myname/projectdir
├── main.go
└── db
├── add.go
└── add_test.go
(Here is a terse variation of the files)
db/add.go
package db
func Add(x, y int) int {
return x + y
}
// some other functions that use a and b from `add_test.go`
db/add_test.go
package db
import (
"testing"
)
var (
a = 1
b = 2
)
// test function use variables from add.go
func testAdd(t *testing.T) {
result := add(a, b)
if result != 3 {
t.Error(err)
}
}
Running go test within db/ directory passed, but once I ran go run main go it produced the following error:
db/add.go:: undefined: a
db/add.go:: undefined: b
Seems like add.go cannot find a and b from add_test.go during the build.
main.go
package main
import (
"fmt"
"gitlab.com/myname/projectdir/db"
)
func main() {
res := db.Add(1, 2)
fmt.Println(res)
}
Is this because add_test.go is not included during the build?
This is just the way how go tool works.
_test.go files are compiled only when you run go test. When a package is imported from another package any code from its _test.go files is not used.
Try running go build or go install from inside db package. It will fail.
Relative paths are touchy in Go. For one, I think you need to prefix them with import "./db". Another thing is that you should be in your $GOPATH/src location.
Try this:
move your files under the $GOPATH/src/project and $GOPATH/src/project/db directories.
prefix your import path with ./db for the DB package.
As for the IDE, that's all up to whatever plugins you are using. Try running the tools yourself: golint, go vet, oracle, etc to see the actual go warnings and errors.
Test functions should start with Test. that is what the documentation says.
func TestAdd(t *testing.T) {
result := Add(a, b)
if result != 3 {
t.Errorf("expected 3, got %d ", result)
}
}
Cheers.

Resources