How to import local packages without gopath

后端 未结 8 1925
有刺的猬
有刺的猬 2020-12-07 07:58

I\'ve used GOPATH but for this current issue I\'m facing it does not help. I want to be able to create packages that are specific to a project:

         


        
相关标签:
8条回答
  • 2020-12-07 08:31

    You can use replace

    go mod init example.com/my/foo
    

    foo/go.mod

    module example.com/my/foo
    
    go 1.14
    
    replace example.com/my/bar => /path/to/bar
    
    require example.com/my/bar v1.0.0
    

    foo/main.go

    package main
    import "example.com/bar"
    
    func main() {
        bar.MyFunc()
    }
    

    bar/go.mod

    module github.com/my/bar
    
    go 1.14
    

    bar/fn.go

    package github.com/my/bar
    
    import "fmt"
    
    func MyFunc() {
        fmt.Printf("hello")
    }
    

    Importing a local package is just like importing an external pacakge

    except inside the go.mod file you replace that external package name with a local folder.

    The path to the folder can be full or relative /path/to/bar or ../bar

    • https://github.com/golang/go/wiki/Modules#when-should-i-use-the-replace-directive
    • https://thewebivore.com/using-replace-in-go-mod-to-point-to-your-local-module/
    0 讨论(0)
  • 2020-12-07 08:33

    I have a similar problem and the solution I am currently using uses Go 1.11 modules. I have the following structure

    - projects
      - go.mod
      - go.sum
      - project1
        - main.go
      - project2
        - main.go
      - package1
        - lib.go
      - package2
        - lib.go
    

    And I am able to import package1 and package2 from project1 and project2 by using

    import (
        "projects/package1"
        "projects/package2"
    )
    

    After running go mod init projects. I can use go build from project1 and project2 directories or I can do go build -o project1/exe project1/*.go from the projects directory.

    The downside of this method is that all your projects end up sharing the same dependency list in go.mod. I am still looking for a solution to this problem, but it looks like it might be fundamental.

    0 讨论(0)
提交回复
热议问题