So I'm pretty new to go and I'm trying to follow this tutorial -
http://thenewstack.io/make-a-restful-json-api-go/
Right now, this is my file structure -
EdData/
dataEntry/
populateDb.go
main.go
handlers.go
routes.go
When I run go run main.go, I get this error ./main.go:11: undefined: NewRouter
This is what my main.go looks like -
package main
import (
"net/http"
"log"
)
func main() {
router := NewRouter()
log.Fatal(http.ListenAndServe(":8080", router))
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
This is what my routes.go looks like
package main
import (
"net/http"
"github.com/gorilla/mux"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes[]Route
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
return router
}
var routes = Routes{
Route {
"Index",
"GET",
"/",
Index,
},
}
and this is what my handlers.go looks like
package main
import (
"fmt"
"net/http"
)
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "WELCOME!")
}
When I try and build routes.go, I get that Index is undefined, and when I try and build handlers.go, I get
# command-line-arguments
runtime.main: undefined: main.main
How do I get this to run? Also, where do I execute the go run command? Do I need to manually build all the dependent files?
From the go run help:
usage: run [build flags] [-exec xprog] gofiles... [arguments...]
Run compiles and runs the main package comprising the named Go source files.
A Go source file is defined to be a file ending in a literal ".go" suffix.
Only the files passed to go run will be included in the compilation (excluding imported packages). Therefore, you should specify all of your Go source files when using go run:
go run *.go
# or
go run main.go handlers.go routes.go
Related
main_test.go
package main_test
import (
"log"
"os"
"testing"
"."
)
func TestMain(m *testing.M) {
a = main.App{}
a.Init(
os.Getenv("TEST_DB_USERNAME"),
os.Getenv("TEST_DB_PASSWORD"),
os.Getenv("TEST_DB_NAME"))
ensureTableExists()
code := m.Run()
clearTable()
os.Exit(code)
}
app.go
package main
import (
"database/sql"
"fmt"
"log"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
type App struct {
Router *mux.Router
DB *sql.DB
}
func (a *App) Init(user, password, dbname string) {
connection := fmt.Sprintf("user=%s password=%s dbname=%s", user, password, dbname)
var err error
a.DB, err = sql.Open("postgres", connection)
if err != nil {
log.Fatal(err)
}
a.Router = mux.NewRouter()
}
func (a *App) Run(addr string) { }
main.go
package main
import "os"
func main() {
a := App{}
a.Init(
os.Getenv("APP_DB_USERNAME"),
os.Getenv("APP_DB_PASSWORD"),
os.Getenv("APP_DB_NAME"))
a.Run(":8080")
}
Hey everyone, I am brand new to Golang and working with some tutorials. In the tutorial, they are using the import statement "." which is throwing an error for me. The exact error is "Non-canonical import-path." I tried using a relative path and full path to access the main file in my project but when I use anything other than "." the var a.main.App throws an error saying that main is an unresolved type. My $GOPATH is set to c:/users/me/go/src my project lives in the src folder. I am not entirely sure what is wrong my code at the moment. If it is something glaringly obvious I apologize.
Here is what I am trying to import. This lives in a file called app.go which is called through main.go
type App struct {
Router *mux.Router
DB *sql.DB
}
You don't need to import main for using struct App. You simply change the package of main_test to main then you can able to use that struct, like below i simply passed the main_test file.
package main
import (
"os"
"testing"
)
func TestMain(m *testing.M) {
a := App{}
a.Init(
os.Getenv("TEST_DB_USERNAME"),
os.Getenv("TEST_DB_PASSWORD"),
os.Getenv("TEST_DB_NAME"))
ensureTableExists()
code := m.Run()
clearTable()
os.Exit(code)
}
Here what i get from execute the test:
Success: Tests passed.
I'm trying to build a Go project using the layout as described in Go Project Layout
I'm using go 1.9.2 on Ubuntu. My project layout is as follows
$GOPATH/src/github.com/ayubmalik/cleanprops
/cmd
/cleanprops
/main.go
/internal
/pkg
/readprops.go
The file cmd/cleanprops/main.go is referring to the cleanprops package i.e.
package main
import (
"fmt"
"github.com/ayubmalik/cleanprops"
)
func main() {
body := cleanprops.ReadProps("/tmp/hello.props")
fmt.Println("%s", body)
}
The contents of internal/pkg/readprops.go are:
package cleanprops
import (
"fmt"
"io/ioutil"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func ReadProps(file string) string {
body, err := ioutil.ReadFile(file)
check(err)
fmt.Println(string(body))
return body
}
However when I build cmd/cleanprops/main.go, from inside directory $GOPATH/src/github.com/ayubmalik/cleanprops, using command:
go build cmd/cleanprops/main.go
I get the following error:
cmd/cleanprops/main.go:5:2: no Go files in /home/xyz/go/src/github.com/ayubmalik/cleanprops
What am I missing?
The document suggests this structure:
$GOPATH/src/github.com/ayubmalik/cleanprops
/cmd
/cleanprops
/main.go
/internal
/pkg
/cleanprops
/readprops.go
Import the package like this. The import path matches the directory structure below $GOPATH/src.
package main
import (
"fmt"
"github.com/ayubmalik/cleanprops/internal/pkg/cleanprops"
)
func main() {
body := cleanprops.ReadProps("/tmp/hello.props")
fmt.Println("%s", body)
}
This question already has answers here:
go build works fine but go run fails
(3 answers)
Closed 7 years ago.
I'm new to Go, but I'm trying to create a RESTful API using Gorilla Mux to create my router based on this article http://thenewstack.io/make-a-restful-json-api-go/
I have a Router file with the below code in it.
package main
import (
"net/http"
"github.com/gorilla/mux"
)
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}
return router
}
var routes = Routes{
Route{
"Index",
"GET",
"/",
Index,
},
}
And in my Main.go I have this:
package main
import (
"log"
"net/http"
)
func main() {
router := NewRouter()
log.Fatal(http.ListenAndServe(":8080", router))
}
From what I know about Go and how to call a method in one file from another this should work. But when I run: go build Main.go I get this error in my console:
go run Main.go
# command-line-arguments
./Main.go:10: undefined: NewRouter
I've run go get in my src folder which has all my files in it to get gorilla, but that didn't fix it. What am I doing wrong here?
If your main package consists of multiple .go files, you have to pass all to go run, e.g.:
go run Main.go Router.go
I have two files main.go and group.go... it looks something like this
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// Creates a gin router with default middlewares:
// logger and recovery (crash-free) middlewares
router := gin.Default()
v1 := router.Group("/v1")
{
v1.GET("/", func (c *gin.Context) {
c.JSON(http.StatusOK, "{'sup': 'dup'}")
})
groups := v1.Group("/groups")
{
groups.GET("/", groupIndex)
groups.GET("/:id", groupShow)
groups.POST("/", groupCreate)
groups.PUT("/:id", groupUpdate)
groups.DELETE("/:id", groupDelete)
}
}
// Listen and server on 0.0.0.0:8080
router.Run(":3000")
}
So the methods groupIndex, groupCreate, groupUpdate, etc are located in another file under routes/group.go
package main
import (
"strings"
"github.com/gin-gonic/gin"
)
func groupIndex(c *gin.Context) {
var group struct {
Name string
Description string
}
group.Name = "Famzz"
group.Description = "Jamzzz"
c.JSON(http.StatusOK, group)
}
func groupShow(c *gin.Context) {
c.JSON(http.StatusOK, "{'groupShow': 'someContent'}")
}
func groupCreate(c *gin.Context) {
c.JSON(http.StatusOK, "{'groupShow': 'someContent'}")
}
func groupUpdate(c *gin.Context) {
c.JSON(http.StatusOK, "{'groupUpdate': 'someContent'}")
}
func groupDelete(c *gin.Context) {
c.JSON(http.StatusOK, "{'groupDelete': 'someContent'}")
}
But when I try to compile I get the following error
stuff/main.go:21: undefined: groupIndex
stuff/main.go:23: undefined: groupShow
stuff/main.go:24: undefined: groupCreate
stuff/main.go:25: undefined: groupUpdate
stuff/main.go:26: undefined: groupDelete
I'm super new to go, but I thought if you put files in the same package, then they'll have access to each other. What am I doing wrong here?
There are two ways to fix this:
Move group.go to the same directory as main.go.
Import group.go as a package. Change the package declaration on group.go to:
package routes // or the name of your choice
Export the functions by starting them with a capital letter:
func GroupIndex(c *gin.Context) {
Import the package from main:
import "path/to/routes"
...
groups.GET("/", routes.GroupIndex)
The document How To Write Go Code explains this and more.
I have a small go lang project which in the main.go file has a few handlers that refer to session related methods in a session.go file. Both have package main at the top of the file. The functions in the session.go file all begin with an uppercase letter (i.e. they are public/exported methods). Yet when I run the main.go file, it says the methods located in session.go and called from main.go are undefined. Why is that, how to fix it.
I am running the project like go run main.go
main.go
func logout(w http.ResponseWriter, r *http.Request) {
ClearSession(w, r)
....
}
session.go
func ClearSession(w http.ResponseWriter, r *http.Request) {
}
As #ptd said, the command needs all the files named.
I prefer use another package:
/ main.go
|_session/
|_session.go
|_validations.go
|_errors.go
So, you can organize your code and simplify your named files.
e.g.:
file: main.go
package main
import "session"
func main() {
var validator session.Validator
var session session.Session
...
if session.IsValid() == false {
// return session.InvalidSession
fmt.Printf("ERROR: %v", session.InvalidSession)
}
}
file: errors.go
import "errors"
var (
InvalidSession = errors.New("[Your error message]"
)
Then you can use:
go run main.go