Create a Go module

  • 原创
  • Madman
  • /
  • /
  • 0
  • 2888 次阅读

Golang.jpg

Synopsis: 使用 Go Modules 管理模块

1. 创建公共模块: go-utils

C:\Users\wangy>D:
D:\>cd GoCodes
D:\GoCodes>mkdir go-utils
D:\GoCodes>cd go-utils
D:\GoCodes\go-utils>go mod init github.com/wangy8961/go-utils
go: creating new go.mod: module github.com/wangy8961/go-utils

D:\GoCodes\go-utils>mkdir greetings
D:\GoCodes\go-utils>cd greetings

使用 Goland 打开 D:\GoCodes\go-utils 目录,在 greetings 目录下创建 greetings.go 文件:

package greetings

import "fmt"

// Hello returns a greeting for the named person.
func Hello(name string) string {
    // Return a greeting that embeds the name in a message.
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message
}

2. 在 hello 模块中调用 go-utils 模块中的代码

D:\GoCodes\go-utils\greetings>cd ..\..
D:\GoCodes>mkdir hello
D:\GoCodes>cd hello

使用 Goland 打开 D:\GoCodes\hello 目录,创建 hello.go 文件:

package main

import (
    "fmt"

    "github.com/wangy8961/go-utils/greetings"
)

func main() {
    // Get a greeting message and print it.
    message := greetings.Hello("Madman")
    fmt.Println(message)
}

在 CMD 中尝试运行:

D:\GoCodes\hello>go run hello.go
hello.go:6:2: cannot find module providing package github.com/wangy8961/go-utils/greetings: working directory is not part of a module

我们需要创建一个新模块:

D:\GoCodes\hello>go mod init hello
go: creating new go.mod: module hello

再次运行:

D:\GoCodes\hello>go run hello.go
go: finding module for package github.com/wangy8961/go-utils/greetings
hello.go:6:2: cannot find module providing package github.com/wangy8961/go-utils/greetings: module github.com/wangy8961/go-utils/greetings: git ls-remote -q origin in D:\GoCodes\pkg\mod\cache\vcs\4198013b20472f12383aa49f4d08ebf23a98c0d78ed27e0079374f5ac333bd32: exit status 128

因为我们的 go-utils 模块还没有发布到 Github 上,所以找不到。我们需要手动修改 go.mod 文件,让 Go Modules 在本地文件系统中去查找 go-utils 模块:

module hello

go 1.15

replace github.com/wangy8961/go-utils => ../go-utils

然后运行编译命令:

D:\GoCodes\hello>go build
go: found github.com/wangy8961/go-utils/greetings in github.com/wangy8961/go-utils v0.0.0-00010101000000-000000000000

此时 go.mod 文件内容自动更新如下:

module hello

go 1.15

replace github.com/wangy8961/go-utils => ../go-utils

require github.com/wangy8961/go-utils v0.0.0-00010101000000-000000000000

假设 go-utils 模块已发布并设置了tag v0.0.1,那么 go.mod 的内容可能是 require github.com/wangy8961/go-utils v0.0.1 // indirect

运行:

D:\GoCodes\hello>hello.exe
Hi, Madman. Welcome!
分类: Go
标签: Go Modules
未经允许不得转载: LIFE & SHARE - 王颜公子 » Create a Go module

分享

作者

作者头像

Madman

如需 Linux / Python 相关问题付费解答,请按如下方式联系我

0 条评论

暂时还没有评论.

专题系列

文章目录