2021-12-04 19:24:42
在GitHub上发布Go语言项目并供他人引用的步骤如下:
一、Go工作区与项目结构bin/:存放编译生成的可执行文件。
pkg/:存放编译生成的包归档文件(.a文件)。
src/:存放所有Go源代码,需按import路径组织(如github.com/user/projectname)。
创建项目目录在$GOPATH/src下按GitHub路径结构创建包目录。例如,用户名为username,包名为newmath:
mkdir -p $GOPATH/src/github.com/username/newmathcd $GOPATH/src/github.com/username/newmath初始化Git仓库
git initgit remote add origin编写包代码创建Go源文件(如sqrt.go),实现包功能:
package newmathfunc Sqrt(x float64) float64 { /* 实现代码 */ return 0 }提交并推送代码
git add .git commit -m 'Initial commit of newmath package'git push -u origin master其他开发者引用方式通过go get命令获取包,并在代码中导入:
go get github.com/username/newmathimport "github.com/username/newmath"创建项目目录在$GOPATH/src下创建命令目录。例如,命令名为hello:
mkdir -p $GOPATH/src/github.com/username/hellocd $GOPATH/src/github.com/username/hello初始化Git仓库
git initgit remote add origin编写命令代码创建hello.go文件,定义main函数作为程序入口:
package mainimport "fmt"func main() { fmt.Println("Hello, Go!") }提交并推送代码
git add .git commit -m 'Initial commit of hello command'git push -u origin master其他开发者安装方式通过go get下载源代码,再用go install编译并安装到$GOPATH/bin:
go get github.com/username/hellogo install github.com/username/hello安装后可直接在命令行执行hello。
pkg/目录的包归档文件和bin/目录的可执行文件无需提交到Git,它们可通过源代码重新生成。
在.gitignore中添加以下内容:bin/pkg/
Go Modules的普及:虽然GOPATH的重要性下降,但在非模块模式下或理解项目结构时仍需关注。
通过上述步骤,你可以高效地将Go语言项目发布到GitHub,并允许其他开发者通过go get和go install轻松引用和安装。关键点包括: