把 go 程式相依模組的來源改為 local

Yi Jyun
Aug 7, 2021

--

紀錄如何把程式所相依且還在開發中的 module 來源。改為本機端的檔案。

“example.com/theirmodule” Module

本機這邊 “example.com/theirmodule/pkg” 底下的 say 函數,如下所定義。

// sayhello module 位於本機的 /home/user/sayhello/pkg/say.go
package pkg
import (
"fmt"
)
func Say(msg string) {
fmt.Println(msg)
}

主程式

此程式 import “example.com/theirmodule”,並使用其 pkg 底下的 say 函數。

// main 程式. (/home/user/test/main.go)
package main
import (
"example.com/theirmodule/pkg"
)
func main() {
pkg.Say("abc")
}

在目錄下輸入 go mode edit -request加入相依模組,並執行 go mod edit -replace 來把模組替換掉成本機的目錄。

$ go mod edit -require=example.com/theirmodule@v0.0.0
$ go mod edit -replace=example.com/theirmodule@v0.0.0=/home/user/sayhello

這時候會看到 go.mod 裡面的 example.com/theirmodule 。來源被指到 /home/user/sayhello

$ cat go.mod
module hello
go 1.16require example.com/theirmodule v0.0.0replace example.com/theirmodule v0.0.0 => /home/user/sayhello

Reference

  1. Requiring module code in a local directory
  2. Using “replace” in go.mod to point to your local module

--

--