首页 > 解决方案 > 去不解决 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 获取它们?

标签: godependency-managementpackage-managers

解决方案


问题是这个 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 版本(和包版本)编写的,它很可能无法工作,或者在某种程度上会被破坏。


推荐阅读