-1

I am trying to learn how to build a webserver using go and mux. I am importing mux to the main.go file as import github.com/gorilla/mux. However, when I am trying to run the code. I get the following error

no required module provides package github.com/gorilla/mux: go.mod file not found in current directory or any parent directory; see 'go help modules'

My GOPATH is /Users/michiokaku/Study/go

The overall structure of my directories is

go___
     pkg
     bin
     my_codes___
                main.go

Inside pkg, I found a directory named mux@v1.8.0 in the path pkg/mod/github.com/gorilla. I think this is what I downloaded using go get -u github.com/gorilla/mux. But when the code is running, I am getting errors.

What is the issue here? How do I solve this?

PS: I am using mac.

Michio Kaku
  • 49
  • 1
  • 6

1 Answers1

2

Read through Tutorial: Getting Started with Go, if you haven't seen it already. It matches your situation pretty closely.

In short:

  • Run go mod init example.com/projectname, replacing the last argument with the name for your module. This will create a go.mod file in the current directory that will track your dependencies. Your module's name will be a prefix for all packages within your module.
  • Run go mod tidy or go get github.com/gorilla/mux to add github.com/gorilla/mux as a dependency.

You mentioned you saw a directory pkg/mod/github.com/gorilla earlier. This is part of Go's module cache, shared by all projects.

Jay Conrod
  • 28,943
  • 19
  • 98
  • 110
  • I followed this. and I am getting an error saying, import cycle not allowed – Michio Kaku Jul 07 '21 at 17:37
  • 1
    @MichioKaku That error happens if a package imports itself directly or indirectly. In the `go mod init` command, did you name your project `github.com/gorilla/mux`? If so, change the name to something else by editing the module line in go.mod or by running `go mod edit -module=example.com/somethingelse`. If not, please add more info. – Jay Conrod Jul 07 '21 at 18:57
  • What should I write as something else here? I didn’t really understand your suggestion. Can you elaborate? Can I simply replace github.com/mypackage or something like that? And Use the same name to import it into my go code? – Michio Kaku Jul 08 '21 at 02:54
  • @MichioKaku update your question by adding the contents of the `go.mod` file, and also add the whole import-cycle error message, it usually lists the packages in the cycle making it quite clear where the problem is. – mkopriva Jul 08 '21 at 03:46
  • 1
    @MichioKaku If you're uploading your project anywhere that others might import it, use a name that matches the repository location. For GitHub, that's something like github.com/yourid/yourrepo. If no one will import packages in your project, you can use any valid name like "example" or "local" or "test". – Jay Conrod Jul 08 '21 at 15:50