[Golang] go mod use

Go mod tutorial on the use of outside too much, three cases talk about my own use I have here.

 

Ready to work:

1, the new file plus gomod_test.

2, enter the command in the directory go mod init gomod_test

 

Case 1: the more common case, cited github package

For example I have the following code main.go

package main

import (
    "fmt"

    "github.com/name/foo"
)

func main() {
      foo.Foo()    
}

Direct command  Go MOD Tidy , then you can go build compiled

 

Case 2: reference works in their own package

Directory structure is as follows 

gomod_test

  |-----main.go

  | ----- mypackage

      | --------- mypackage.go

 

To reference main.go mypackage package, into the following codes.

Note that  "gomod_test / mypackage" , gomod_test is above us go mod init module name of gomod_test, mypackage your package directory

package main

import (
    "fmt"
   "gomod_test/mypackage"  
    "github.com/name/foo"
)

func main() {
      foo.Foo()   
      mypackage.XXX() 
}

  

Case 3: refer to the local package

The reason for this is: Let us rely on the github.com/name/mylib this library, but we need to build in a pure network without external network environment, this time go get less than github code, we need to replace Alternatively the package cost.

1, first of all I need to download github.com/name/mylib down, you can download the zip, you can also clone, to the project root directory

2, edit go.mod file add the following line (mod edit commands can also be edited with go, some of the more orthodox)

replace github.com/name/mylib=> ./mylib

To ensure consistency with ./mylib directory of your download code

Directory structure is as follows

gomod_test

  |-----main.go

  | ----- mypackage

      | --------- mypackage.go

  |-----mylib

      |---------mylib.go

 

main.go read as follows

package main

import (
    "fmt"
    "gomod_test/mypackage"  
    "github.com/name/mylib"
    "github.com/name/foo"
)

func main() {
      foo.Foo()   
      mypackage.XXX()
      mylib.DoXXX()
}

 

other

1, if you want to copy will depend on the vendor can go mod vendor command

2, if you want to use the vendor's compiler dependent libraries in the executable file can use the command  go build -mod = vendor

Guess you like

Origin www.cnblogs.com/mrblue/p/11277100.html