others-how to solve 'go run: cannot run non-main package' when running golang program ?

Problem

When we run a golang ( or go) progam as follows:

go run main.go

sometimes , we get this error:

go run: cannot run non-main package

Why do this error happen? The golang program is correct, I promise!!!

Environment

  • go version go1.14

The code

The main code of the program is:

package gin

import "github.com/gin-gonic/gin"

func main() {
        r := gin.Default()
        r.GET("/ping", func(c *gin.Context) {
                c.JSON(200, gin.H{
                        "message": "pong",
                })
        })
        r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Reason

There should exist a package named ‘main’ in the program. The first statement in a Go source file must be package name. Executable commands must always use package main.

Solution

We should change the code as follows:

package main

import "github.com/gin-gonic/gin"

func main() {
        r := gin.Default()
        r.GET("/ping", func(c *gin.Context) {
                c.JSON(200, gin.H{
                        "message": "pong",
                })
        })
        r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Run the app again, No error messages ,It works!

By the way

Go programs are organized into packages. A package is a collection of source files in the same directory that are compiled together. Functions, types, variables, and constants defined in one source file are visible to all other source files within the same package.