I wish to create a large project, so I need to create some kind of folder structure. I am quite new to Go, but, as I understand, the way to do it is to create packages, right? I am using Go modules, I have tried many different solutions found here and on Google, but none of them seem to work for me.
All I want to for now, is import exported function from example.go file into main.go
Folder structure is as follows:
client
example
---example.go
go.mod
go.sum
main.go
module exampleapp
go 1.12
require (
github.com/gin-gonic/contrib v0.0.0-20190408155029-b5986969cb50
github.com/gin-gonic/gin v1.4.0
)
package main
import (
"net/http"
"exampleapp/example"
)
package example
import (
"net/http"
"github.com/gin-gonic/gin"
)
func GetAllEmployees(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
}
For the most part, when I try to add package in main.go, VSCode automatically removes the line and in the main function says that GetAllEmployees is not defined. I managed to catch error package before the package is removed, it says -
"imported and not used: "exampleapp/example"Am I wrong to use "exampleapp/example" module name exampleapp here? I tried without the exampleapp and "./example/example", but then I get an error that says it cannot find module for path.
Help would be highly appreciated, as I have been stuck on this for quite some time and can't figure out, what am I missing here.
In Go, a package is a directory of .go files, and packages form the basic building blocks of a Go program. Using packages, you organize your code into reusable units. A module, on the other hand, is a collection of Go packages, with dependencies and versioning built-in.
You cannot import the main package. Any shared code should go in a separate package, which can be imported by main (and other packages).
Both single and multiple packages can be imported one by one using the import keyword.
It should be like that (main.go):
package main
import (
"exampleapp/example"
)
func main() {
example.GetAllEmployees(...)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With