Golang import cycle not allowed - go

I am creating a restful api in GO and every method essentially interacts with the database. The specific statement that I use to open a database connection is
db,err := sql.Open("postgres", "user=postgres password=password dbname=dbname sslmode=disable")
if err != nil {
log.Fatal(err)
println(err)
}
It is very simple but the issue is that once I want to change something inside that statement then I have to change it for all other methods that have that statement . I am trying to do a dependency injection or something of that nature so that I can have that statement or value in 1 place and just reference it. I am getting an import cycle not allowed error though like Import cycle not allowed . This is my project structure
What I have done is that in the Config.go I have written this
package Config
const Connect = "user=postgres password=password dbname=dbname sslmode=disable"
Then in the Listings.go I put this
package Controllers
import (
"net/http"
"database/sql"
"../Config"
)
func Listing_Expiration(w http.ResponseWriter, r *http.Request) {
db,err := sql.Open("postgres",Config.Connect)
if err != nil {
log.Fatal(err)
println(err)
}
notice I have the import ../Config and the Config.Connect but when I compile that I get import cycle not allowed . I have been trying to solve this issue but haven't been able to.

Yes, Go doesn't allow to have cycled imports. In your example you have 2 packages Config and Controllers. When you build a code, Controllers package requires Config package, then Config requires Controllers and it's endless. You should refactor your code to make Config package separated from Controllers, and only used by it. Also, you can make some common package, imported to Controllers and Config.

I got the same error. But in my case, I imported the package itself inside the file. so you can check if you did the same mistake.

Go does NOT allow import cycles. So you need to fix it. In your case, Controller and Config are importing each other, you are not allowed to do that.
I wrote a detailed blog about how you can deal with it. Refer https://jogendra.dev/import-cycles-in-golang-and-how-to-deal-with-them
Use interfaces.
Making use of go:linkname.

Though, I can't see any import cycle from your code.
Go don't support the import cycle. Based on your question, you must import the controller from the Config Package. You need to remove one of them and refactor your code.
Fore more: https://jogendra.dev/import-cycles-in-golang-and-how-to-deal-with-them

Related

Unable to use functions within imported package

My current Directory is setup as follows:
-- /webserver
|
/ftp
|-> ftp.go
|-> go.mod
|->server.go
|->go.mod
Server.go page heading
package main
import (
[..]
"../webserver/ftp" // issue package
)
func main() {
[..]
ftp.test()
}
ftp.go page
package ftp
import "fmt"
func test() {
fmt.Println("YES!")
}
Here's the part I cant seem to understand in the console "PROMBLEMS" tab. The ftp.go file gets saved. Before I save the server.go file with "../webserver/ftp/" the console displays this:
When I save server.go it removes "./webserver/ftp", I went as far as adding it into the go src to make it "ftp" instead of "../webserver/ftp". I get the same result.
Not sure what I am doing wrong.
Basically what i want to accomplish is:
have a functions folder and have the functions in that folder (functions.go) to keep the server.go page as clean as possible.
You have several problems here.
ftp/go.mod should not exist. While it is possible to have multiple Go modules in a single repository, this is very advanced usage, and is rarely useful. Unless you absoultely know that you need this capability, and are already exremely comfortable with creating and publishing Go modules, don't do this.
Go does not support relative imports. import "../webserver/ftp" is an invalid import path*. Use the fully qualified import path, i.e. import "github.com/username/projectname/webserver/ftp"
The path to use here depends on the module name you've declared on the module line of your your top-level go.mod file.
You cannot import unexported values.
You've defined func test() string in ftp.go. This is unexported, by virtue of beginning with a lowercase letter. Only functions, variables, or other symbols which begin with a capital letter are exported in Go. Try func Test() string instead.
*Some will say "But I used import ".../foo" and it worked!". Yes, it can work under very specific circumstances. But its behavior is not reliable, so you should never rely on this, except in very specific testing types of situations.

How to call a Go Cloud Function from another Go Cloud Function in GCP

Goal: I want to reuse many Go functions from two Go functions with HTTP triggers.
What I have tried and steps to reproduce the problem:
In GCP, create a new Go 1.11 Cloud Function, HTTP Trigger
Name it: MyReusableHelloWorld
In function.go, paste this:
package Potatoes
import (
"net/http"
)
// Potatoes return potatoes
func Potatoes(http.ResponseWriter, *http.Request) {
}
In go.mod, paste this: module example.com/foo
In function to execute, paste this: Potatoes
Click on deploy. It works.
Create another Go serverless function in GCP
In function. go, paste this:
// Package p contains an HTTP Cloud Function.
package p
import (
"encoding/json"
"fmt"
"html"
"net/http"
"example.com/foo/Potatoes"
)
// HelloWorld prints the JSON encoded "message" field in the body
// of the request or "Hello, World!" if there isn't one.
func HelloWorld(w http.ResponseWriter, r *http.Request) {
var d struct {
Message string `json:"message"`
}
if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
fmt.Fprint(w, "error here!")
return
}
if d.Message == "" {
fmt.Fprint(w, "oh boy Hello World!")
return
}
fmt.Fprint(w, html.EscapeString(d.Message))
}
In go.mod, paste this: module example.com/foo
In function to execute, paste this: HelloWorld
Click on deploy. It doesn't work. You have the error: unknown import path "example.com/foo/Potatoes": cannot find module providing package example.com/foo/Potatoes
I have also tried all kinds of combinations for the module/packages to import.
I have tried without the example.com/ part.
Other smaller issue:
The functions I want to reuse could all be in the same file and don't really need any trigger, but it doesn't seem that having no trigger is possible.
Related questions and documentation with which I could not achieve my goal:
How can I use a sub-packages with Go on Google Cloud Functions?
https://github.com/golang/go/wiki/Modules , section go.mod
You can’t invoke a cloud function from another one, because each function is in its own container independently.
So If you want to deploy the function with a dependency that can't be downloaded from a package manager you need to put the code together like here and deploy using the CLI
It is likely each cloud function defined in the console is independent of the other. If you want code reuse, it's best to structure it as per the following document and deploy it using gcloud command.
https://cloud.google.com/functions/docs/writing/#structuring_source_code
You are mixing things: package management and function deployment.
When you deploy a Cloud Function, if you want to (re)use it, you have to call if with http package.
If you build a package that you want to include in your source code, you have to rely on package manager. With Go, Git repository, like Github, is the best way to achieve this (Don't forget to perform a release and to name it as expected by Go mod: vX.Y.Z)
Here your code can't work without more engineering and package publication/management.
I achieve the same things but with a Dockerfile and I deplored my code in Cloud Run (that I recommend you if you aren't event oriented and only HTTP oriented. I wrote a comparison on Medium)
Root
go.mod
pkg/foo.go
pkg/go.mod
service/Helloworld.go
service/go.mod
In my helloworld.go, I can reuse the package foo. For this I perform this in my service/go.mod file
module service/helloworld
go 1.12
require pkg/foo v0.0.0
replace pkg/foo v0.0.0 => ../pkg
Then when you build your container, you run your go build service/Helloworld.go from the root directory.

package selection error in for a go function

I am learning from a book the book says to add a couple lines of code, but it throws an error
package main
import (
"./lissajous"
"log"
"net/http"
)
func main() {
handler := func(w http.ResponseWriter, r *http.Request) {
lissajous(w)
}
http.HandleFunc("/", handler) // each request calls handler
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
it throws this error
./server.go:6: imported and not used:
"_/home/zach/Dropbox/Personal/Go_Programming
/The_Go_Programming_Language/ch01/web/lissajous"
./server.go:14: use of package lissajous without selector
the package directory I think is correct, but can't seem to call functions, the set up for the handler is just like that in the book am I missing something?
any help appreciated?
Here are 2 things:
Go doesn't allow unused imports - if you import module you should use it, or temporarily comment out
another way of custom module creation and import recommended. Think like once you will publish it and treat it as being already published. Choose an unique URL for it like github.com/login/repo/super-package/package. However if you are not obliged to publish it right now neither in open source nor private repo. It's recommended to keep it like this in your system. It'lll be easier to start sharing it with colleagues and possibly publish if you wish.

Is it possible a Golang package in subdir not included by default?

I am using a golang package, say name pkgfoo; and the author explicitly said if we want to use a package subpkg under pkgfoo, I need to explicitly import subpkg. I don't understand the reason behind it. Isn't the subpkg automatically imported if I import the top pkg in Golang?
package main
import (
"myownpackage"
"github.com/usera/pkgfoo"
"github.com/usera/pkgfoo/subpkg"
)
func main() {
// Use functions in pkgfoo, and use functions in pkgfoo/subpkg
// ......
http.HandleFunc("/login", login)
err := http.ListenAndServe(":9090", nil) // setting listening port
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
My question is whether I really need import "github.com/usera/pkgfoo/subpkg" statement.
Go packages are constructed from one or more source files, which are organized into folders in the file system. Source files of the same package must be in the same folder.
But in Go there is no "package hierarchy", the "subpackage" term simply refers to the folder of a package being a subfolder of another. We often organize packages to be in folders being subfolders of others because there is some connection between those packages (e.g. a package is used only by another being in the parent folder; or a package in a subfolder is a specific or more special implementation of the package in the parent folder; or simply just a logical grouping - see the end of the answer).
So whenever you do
import "github.com/usera/pkgfoo"
It only imports pkgfoo and no other packages sharing the same path as prefix. If you need github.com/usera/pkgfoo/subpkg too, you also need to explicitly import it:
import (
"github.com/usera/pkgfoo"
"github.com/usera/pkgfoo/subpkg"
}
The Go Blog: Package names on directories used in the standard library:
Directories. The standard library uses like directories crypto, container, encoding, and image to group packages for related protocols and algorithms. There is no actual relationship among the packages in one of these directories; a directory just provides a way to arrange the files. Any package can import any other package provided the import does not create a cycle.

In Go, how to import function directly, without need to prefix with the package name when I call it?

In the Go programming language, why after importing a package do I still have to prefix a method within that package with the package name?
i.e.
import "io/ioutil"
func main() {
content, err = iotuil.ReadFile("somefile.txt")
// etc..
}
Isn't this redundant? In Java, for example, you can do things like importing Files.readAllLines etc without having Files imported.
I guess this doesn't really answer your question, but if you want, you can actually call the methods without explicitly stating the package - just import with a . in front of the names (but this is not recommended; see below):
package main
import (
. "fmt"
. "io/ioutil"
)
func main () {
content, err := ReadFile("testfile")
if err != nil {
Println("Errors")
}
Println("My file:\n", string(content))
}
Note #jimt's comment below - this practice is not advised outside of tests as it could cause name conflicts with future releases. Also, definitely agree with #DavidGrayson's point of being nicer to read/see where things come from.
you can import and rename the package name, eg:
import (
. "fmt" // no name, import in scope
File "io/ioutil" // rename ioutil to File
_ "net" // net will not be available, but init() inside net package will be executed
)
See also https://golang.org/ref/spec#Import_declarations
I can't really speak for the designers of the Go language, but it is nice to be able to quickly tell where the method you are calling is defined. It is also nice to see a list of all the packages your are using at the top of the file. This is not redundant.
As you said, Java requires you to say Files.readAllLines and similarly go requires you to write ioutil.ReadFile.
Import statements in go are not like in java, more like #include in c++. In go, if something isn't imported, you can't use it. If it is imported, you can use it but must be prefixed with the package name. As everyone else said, use import . "packagename" to import a package and not have to prefix.

Resources