How to correctly import a module that executes ioutil.ReadDir in the func init()?

I have two modules, ModuleA and ModuleB, each in a separate folder. The main.go in ModuleA needs to import a package from ModuleB. Inside the init function of the package in ModuleB, it will call “ioutil.ReadDir” and print all the files in the current directory.

My expectation is when importing ModuleB in ModuleA, it should print all files under the folder of ModuleB. However, it actually prints the files under the folder of ModuleA. May I know how to fix it?

go.mod under ModuleA

module ModuleA

go 1.19

replace ModuleB => ../ModuleB

require ModuleB v0.0.0-00010101000000-000000000000

main.go under ModuleA

package main

import "ModuleB"

func main() {
    math.Add(1, 2)
}

math.go in ModuleB

package math

import (
    "fmt"
    "io/ioutil"
    "log"
)

func init() {
    fmt.Println("init moduleB math")
    // ReadDir here
    files, err := ioutil.ReadDir(".")
    if err != nil {
        log.Fatal(err)
    }

    for _, file := range files {
        fmt.Println(file.Name(), file.IsDir())
    }
}

func Add(a, b int) {
    fmt.Println(a + b)
}

folder structure
image

dirname parameter “.” represents the working directory. You can get it with os.Getwd(). You can also get executable’s path with os.Executable().

What are you trying to achieve? Why would you want to read files from a source code directory at run time? Maybe embed package - embed - Go Packages will solve your problem.

In real case, I try put a config file under the directory of ModuleB, and hope through importing ModuleB, I can know the content of that config file.

Hopefully embed will work for you. I’ve never used it so I can’t offer any help. Otherwise, you’ll need to distribute the config file.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.