Search code examples
godependency-managementpackage-managers

Go not resolving GitHub package imports


New to Go/Golang and am trying to understand its package/dependency management system a little better.

I cloned this simple web service repo off GitHub and tried running it with go run main.go. In that main.go file:

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)
    }
}

When I run this (run go main.go) I get:

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)

So it seems Go supports a way of "fetching" other packages from GitHub via HTTP but for some reason when I run it locally, its expecting the packages to be local.

What can I do to fix this so that the other packages are resolved? Why is Go looking for them locally instead of fetching them via the URL?


Solution

  • Problem is that this repo is from pre go modules era and doesn't use any dependency management system. Easiest way to fix it is to try to initialize it as module(if you use go < 1.14 set environment variable GO111MODULE=on):

    go mod init github.com/wpferg/services
    

    And then run:

    go run main.go
    

    it will resolve it's dependencies automatically and try to start the program.

    P.S. But, regarding that it's an older code and it's unclear with what golang version(and packages versions) it was written it's likely that it will not work or, in some way, will be broken.