go - 去不解决 GitHub 包导入
问题描述
Go/Golang 新手,正在尝试更好地理解它的包/依赖管理系统。
我从 GitHub 上克隆了这个简单的 Web 服务存储库,并尝试使用go run main.go
. 在该main.go
文件中:
package main
import (
"log"
"net/http"
"strconv"
"github.com/wpferg/services/httpHandlers"
"github.com/wpferg/services/storage"
"github.com/wpferg/services/structs"
)
const PORT = 8080
var messageId = 0
func createMessage(message string, sender string) structs.Message {
messageId++
return structs.Message{
ID: messageId,
Sender: sender,
Message: message,
}
}
func main() {
log.Println("Creating dummy messages")
storage.Add(createMessage("Testing", "1234"))
storage.Add(createMessage("Testing Again", "5678"))
storage.Add(createMessage("Testing A Third Time", "9012"))
log.Println("Attempting to start HTTP Server.")
http.HandleFunc("/", httpHandlers.HandleRequest)
var err = http.ListenAndServe(":"+strconv.Itoa(PORT), nil)
if err != nil {
log.Panicln("Server failed starting. Error: %s", err)
}
}
当我运行这个 ( run go main.go
) 我得到:
main.go:8:2: cannot find package "github.com/wpferg/services/httpHandlers" in any of:
/usr/local/go/src/github.com/wpferg/services/httpHandlers (from $GOROOT)
/Users/myuser/go/src/github.com/wpferg/services/httpHandlers (from $GOPATH)
main.go:9:2: cannot find package "github.com/wpferg/services/storage" in any of:
/usr/local/go/src/github.com/wpferg/services/storage (from $GOROOT)
/Users/myuser/go/src/github.com/wpferg/services/storage (from $GOPATH)
main.go:10:2: cannot find package "github.com/wpferg/services/structs" in any of:
/usr/local/go/src/github.com/wpferg/services/structs (from $GOROOT)
/Users/myuser/go/src/github.com/wpferg/services/structs (from $GOPATH)
因此, Go似乎支持一种通过 HTTP 从 GitHub “获取”其他包的方式,但由于某种原因,当我在本地运行它时,它期望这些包是本地的。
我能做些什么来解决这个问题,以便解决其他包?为什么 Go 在本地寻找它们而不是通过 URL 获取它们?
解决方案
问题是这个 repo 来自 pre go modules时代并且不使用任何依赖管理系统。修复它的最简单方法是尝试将其初始化为模块(如果您使用 go < 1.14 set environment variable GO111MODULE=on
):
go mod init github.com/wpferg/services
然后运行:
go run main.go
它将自动解决它的依赖关系并尝试启动程序。
PS 但是,关于它是一个较旧的代码,并且不清楚它是用什么 golang 版本(和包版本)编写的,它很可能无法工作,或者在某种程度上会被破坏。
推荐阅读
- aws-api-gateway - 无服务器插件域管理器没有减少资源限制
- ssl - Service Fabric 证书交换。应用程序无法激活
- gradle - IntelliJ Idea - 如何启用 gradle 包装器
- tensorflow - 使用 loadFrozenModel 后如何修改 tensorflowjs 中的辍学率?
- c# - 关于如何实现条件依赖的建议?
- python - Python 3.2 W/Pygame 崩溃
- python - If Else 在类中的方法中不起作用
- java - 如何在不使用 LinkedList 方法的情况下在列表中设置元素
- android - Android - 自动重定向到新活动
- python - 在 Raspberry Pi 3 Stretch 上将默认 Python 3.5.3 升级到 Python 3.7.2