error with "package main" flagging red in the main.go folder

Viewed 4458

I have written a main.go program and declared the package at the beginning of the code but it flagging red as shown below: see the flag on the package main

When I hover on the package, it displays the following:

gopls requires a module at the root of your workspace.
You can work with multiple modules by opening each one as a workspace folder.
Improvements to this workflow will be coming soon, and you can learn more here:
https://github.com/golang/tools/blob/master/gopls/doc/workspace.md.

I'd require help on how I can pass this error. Thanks a lot.

4 Answers

You need to run the command go mod init from your command line at the root of the project. It looks like you ran it from go-microservice/prod-api, but it should be run at the same place where your .git lives. If prod-api is in fact the root of the git project, then you need to open that folder in VSCode instead of go-microservice.

I'm getting started with golang, so I'm not sure if this would help you.

This error was showing up here in VS Code, and to solve it I needed to clone an empty github repo into a new folder, to add the main.go file later.

I was able to add, commit and push changes. The lint error is now gone.

In my case, .git folder is located upwards, and not alongside main.go:

\my-app
  |
  |__ \backend
      |__ go.mod
      |__ main.go
  |__ \frontend
  |__ \.git

Within the backend folder the go.mod was generated with

go mod init github.com/<your-username>/my-app

It seems GitHub changed the default branch from master to main. If you use github, check if your in the correct branch, which may be main by default.

If you move hello.go to the root folder of GO-MICROSERVICE from prod-api, then you will not have an error.

Related