I can write almost all the functions in the module I created, except the one thing I need most is undefined... I really need to use this function
Directory Hierarchy
workdir
main.go
go.mod
go.work
userinfo
userinfo.go
go.mod
workdir/go.mod
module example.com/workdir
go 1.21.5
workdir/go.work
go 1.21.5
use (
.
./userinfo
)
workdir/userinfo/go.mod
module example.com/userinfo
go 1.21.5
The first idea was simple... I was tired of typing username and password into the database over ssh every time, so I wanted to store the username and password in the config, and have it pull them out whenever I needed them.
So I wrote a bunch of functions in the workdir/userinfo
directory to encrypt the username and password with the rsa algorithm, set the public and private keys to this and that, etc.
And finally, I put in a function that would always enter my commands exactly as they should be.
func comExec(dbCommand string) (string, error) {
var result string
// Load private key for decryption
privateKey, err := LoadPrivateKey()
if err != nil {
return "", err
}
// Read and decrypt credentials
user, password, err := ReadCredentials(privateKey)
if err != nil {
return "", err
}
//execute command with db argument
cmd := exec.Command("myDatabase", dbCommand, "--address=http://localhost.com/db", "--username", user, "--password", password)
var out bytes.Buffer
cmd.Stdout = &out
err = cmd.Run()
if err != nil {
return "", err
}
result = out.String()
return result, nil
}
Obviously, while I was creating this module, I could type go run userinfo.go
and everything worked perfectly.
So naturally, I created main.go
in my workdir
, and I put these functions in there.
import (
"fmt"
"strings"
"example.com/userinfo"
)
func main() {
var comm := string
fmt.Scanf("what do you want : %s", &comm)
result, err := userinfo.comExec(comm)
if err != nil {
fmt.Printf("error occurs:", err)
return
}
// Print the fourth part of the command output
outputParts := strings.Split(result, "\n")
if len(outputParts) >= 4 {
fmt.Println(outputParts[3])
} else {
fmt.Println("Insufficient output from command")
}
}
and then, undefined: userinfo.comExec compiler(UndeclaredImportedName)
comes to me.
It's only occurs to comExec
function.
I use vscode, obviously it has automatic completion, and in my userinfo.go, there are bunch of functions, such as decrypt
, encrypt
, generateRSAkeys
etc. vscode can complete those functions when I stopped at userinfo.
but no comExec
only.
I recorded myself, as you can see, when I save the file, imported module disappeared, because there are no function is from the module, actually it exactly there!
You can try commands like go work sync , go mod tidy and go get "example.com/userinfo" . Also better to make comExec to ComExec this can help in making the function exported. You can refer official golang document about working with multiple modules https://go.dev/doc/tutorial/workspaces