Home >Backend Development >Golang >How does go module use local packages (with examples)

How does go module use local packages (with examples)

藏色散人
藏色散人forward
2021-11-26 16:02:442089browse

This article is provided by the go language tutorial column to introduce how to use local packages with go module. I hope it will be helpful to friends in need!

The use of go module is very simple

  1. Initialize go.mod

    go mod init
  2. Organize dependency packages

    go mod tidy
  3. If you want to cache to the vendor directory

    go mod vendor

The dependencies will be automatically resolved after executing the command.
But, if we develop the package locally and do not have a remote warehouse, how to solve the local package dependency problem?

Use replace to replace the remote package with the local package service

Fortunately, go module provides another solution, replace. How to use this replace?
Let's take a look at a basic mod file first

module GoRoomDemo

go 1.12

require (
    github.com/gin-gonic/gin v1.3.0
    github.com/gohouse/goroom v0.0.0-20190327052827-9ab674039336
    github.com/golang/protobuf v1.3.1 // indirect
    github.com/gomodule/redigo v2.0.0+incompatible
    github.com/mattn/go-sqlite3 v1.10.0
    github.com/stretchr/testify v1.3.0 // indirect
    golang.org/x/net v0.0.0-20190320064053-1272bf9dcd53 // indirect
)

This is a simpleGoRoom The dependency package of the framework, if I want to use the local goroom, I only need to use replace

module GoRoomDemo

go 1.12

require (
    github.com/gin-gonic/gin v1.3.0
    github.com/gohouse/goroom v0.0.0-20190327052827-9ab674039336
    github.com/golang/protobuf v1.3.1 // indirect
    github.com/gomodule/redigo v2.0.0+incompatible
    github.com/mattn/go-sqlite3 v1.10.0
    github.com/stretchr/testify v1.3.0 // indirect
    golang.org/x/net v0.0.0-20190320064053-1272bf9dcd53 // indirect
)

replace github.com/gohouse/goroom => /path/to/go/src/github.com/gohouse/goroom
Herepath/to/go/src/github .com/gohouse/goroom is the local package path

In this way, we can happily use the local directory.

The above is the detailed content of How does go module use local packages (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete