Golang中如何构建小型模块
Golang中如何构建小型模块 我想构建一个类似DLL的小模块,并与其他开发者共享。他们将使用它,但无法修改或查看代码。
5 回复
你可以尝试使用插件,但这与构建二进制包并不完全相同。
你无法这样做。仅包含二进制文件的包支持在 Go 1.12 之后已被移除。相关讨论在这里。
是的,你可以这样做 😄 创建一个 main.go 文件:
package main
import "C"
//export Add
func Add(a, b int) int {
return a + b
}
func main() {}
然后使用以下命令构建 😄
Linux:
go build -buildmode=c-shared -o mylib.so main.go
Windows:
go build -buildmode=c-shared -o mylib.dll main.go
macOS:
go build -buildmode=c-shared -o mylib.dylib main.go
在Go中构建可共享的私有模块可以通过以下步骤实现:
1. 创建私有模块
首先初始化模块并设置私有仓库:
# 初始化模块
go mod init github.com/yourcompany/private-module
# 创建主要功能文件
mkdir -p internal/calculator
2. 实现模块功能
创建 internal/calculator/operations.go:
package calculator
import "fmt"
// 导出公开的函数
func Add(a, b int) int {
return a + b
}
func Subtract(a, b int) int {
return a - b
}
// 私有函数(小写开头)
func multiply(a, b int) int {
return a * b
}
// 复杂功能示例
type Calculator struct {
memory int
}
func NewCalculator() *Calculator {
return &Calculator{memory: 0}
}
func (c *Calculator) MemoryAdd(value int) {
c.memory += value
}
func (c *Calculator) GetMemory() int {
return c.memory
}
3. 创建主入口文件
创建 pkg/public_api.go:
package private_module
import (
"github.com/yourcompany/private-module/internal/calculator"
)
// 公开API接口
type Calculator interface {
MemoryAdd(value int)
GetMemory() int
}
// 工厂函数
func NewCalculator() Calculator {
return calculator.NewCalculator()
}
// 公开函数
func Add(a, b int) int {
return calculator.Add(a, b)
}
func Subtract(a, b int) int {
return calculator.Subtract(a, b)
}
4. 配置模块可见性
使用 internal 目录保护内部实现:
your-module/
├── go.mod
├── internal/
│ └── calculator/
│ └── operations.go
├── pkg/
│ └── public_api.go
└── cmd/
└── example/
└── main.go
5. 发布到私有仓库
# 设置私有仓库认证
git init
git add .
git commit -m "Initial commit"
# 推送到私有Git仓库
git remote add origin https://github.com/yourcompany/private-module.git
git push -u origin main
# 设置GOPRIVATE环境变量
go env -w GOPRIVATE=github.com/yourcompany/*
6. 其他开发者使用方式
其他开发者在他们的 go.mod 中添加:
module their-project
go 1.21
require github.com/yourcompany/private-module v1.0.0
replace github.com/yourcompany/private-module => ./local/path/to/module // 本地测试
使用示例:
package main
import (
"fmt"
"github.com/yourcompany/private-module"
)
func main() {
// 使用公开函数
sum := private_module.Add(10, 5)
fmt.Printf("10 + 5 = %d\n", sum)
// 使用接口
calc := private_module.NewCalculator()
calc.MemoryAdd(20)
fmt.Printf("Memory: %d\n", calc.GetMemory())
}
7. 构建和分发选项
选项A:源码分发(推荐)
# 构建vendor包
go mod vendor
# 分发vendor目录
tar -czf private-module-vendor.tar.gz vendor/
选项B:编译为静态库
# 编译为静态库
go build -buildmode=c-archive -o libprivate.a ./pkg
# 生成头文件
// 需要手动创建C头文件或使用cgo包装
选项C:使用Go插件(类似DLL)
// 构建插件
go build -buildmode=plugin -o private.so ./pkg
// 使用插件
plugin, err := plugin.Open("private.so")
if err != nil {
log.Fatal(err)
}
addFunc, err := plugin.Lookup("Add")
if err != nil {
log.Fatal(err)
}
8. 版本控制
使用语义化版本标签:
git tag v1.0.0
git push origin v1.0.0
其他开发者可以指定版本:
go get github.com/yourcompany/private-module@v1.0.0
这种方式可以保护代码不被修改,同时提供清晰的API接口供其他开发者使用。

