I'm testing a simple server app with Gorilla Mux. I keep getting undefined error when running the app. This is the structure of the app
src/ptest/
├── app
│ └── app.go
└── main.go
main.go
package main
import (
"fmt"
"ptest/app"
)
func main() {
fmt.Println("Hello Testing App")
app := App{}
}
app.go
package app
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
type App struct {
Router *mux.Router
}
func (A *App) Run() {
fmt.Println("Listening at :8080")
log.Fatal(http.ListenAndServe(":8080", A.Router))
}
As you can see, I have a main
that initialized app
by importing from ptest/app
. But I am getting an error when I go run *go
:
# command-line-arguments
./main.go:5:2: imported and not used: "ptest/app"
./main.go:10:9: undefined: App
This is my go env
. I am wondering if something not right with my environment?
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/haha/Library/Caches/go-build"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/haha/go"
GORACE=""
GOROOT="/usr/local/go"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GCCGO="gccgo"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
Use App{}
struct by package name. Your are importing the package but not using it. App
struct is declared in app
package. that's why the error.
# command-line-arguments
./main.go:5:2: imported and not used: "ptest/app"
./main.go:10:9: undefined: App
In your program you are trying to initialize an App{}
which does not exist in main.go
.
package main
import (
"fmt"
"ptest/app"
)
func main() {
fmt.Println("Hello Testing App")
app := app.App{}
}
It is well described in Golang Spec for Qualified Identifiers:
A qualified identifier is an identifier qualified with a package name prefix. Both the package name and the identifier must not be blank.
QualifiedIdent = PackageName "." identifier .
A qualified identifier accesses an identifier in a different package, which must be imported. The identifier must be exported and declared in the package block of that package.
math.Sin // denotes the Sin function in package math