Search code examples
gogo-modules

How to go mod get local package?


I want go.mod get a folder inside the selfCheck(get package inside selfCheck folder).

selfCheck/encrypt , selfCheck/searchSchool

my screenshots is here

enter image description here

(don't mind vendor file. i'll remove it.)


Solution

  • You don't need to require a folder in the project itself in go.mod files. go.mod is only requireing external packages from other repositories.

    I wrote a blogpost on starting with Go that covers this question. https://marcofranssen.nl/start-on-your-first-golang-project

    I also wrote a whole bunch more articles on Go https://marcofranssen.nl/categories/golang

    In summary what you should do it use the full url of your git repository so other projects can depend on it as a best practice.

    e.g.

    go mod init github.com/your-user/selfcheck

    Once you did that your go.mod file looks like this.

    module github.com/your-user/selfcheck
    
    go 1.17
    

    Please note camel casing is not the way you name go packages. Go packages should be all lowercase.

    Now if you want to create sub packages as you are asking for you should create folders. e.g. your project could look like this.

    $ tree selfcheck
    selfcheck
    ├── go.mod
    ├── main.go
    └── searchschool
        └── searchschool.go
    
    1 directory, 3 files
    

    Now to reference code from the searchschool package you can do the following in main.go.

    package main
    
    require (
        "fmt"
    
        "github.com/your-user/selfcheck/searchschool"
    )
    
    func main() {
        fmt.Println(searchschool.Excute())
    }
    

    Please note all functions have to start with an uppercase to access them outside of the searchschool package. E.g. searchschool/searchschool.go

    package searchschool
    
    func Execute() string {
        return privateFunc() + "!"
    }
    
    func privateFunc() string {
        return "Hello World"
    }