英文:
Go cannot call NewRouter() function
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是Go的新手,但我正在尝试使用Gorilla Mux创建一个RESTful API,根据这篇文章http://thenewstack.io/make-a-restful-json-api-go/来创建我的路由器。
我有一个包含以下代码的路由器文件。
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,
},
}
在我的Main.go文件中,我有以下代码:
package main
import (
"log"
"net/http"
)
func main() {
router := NewRouter()
log.Fatal(http.ListenAndServe(":8080", router))
}
根据我对Go语言和如何从一个文件中调用另一个方法的了解,这应该可以工作。但是当我运行go build Main.go
时,控制台显示以下错误:
go run Main.go
# command-line-arguments
./Main.go:10: undefined: NewRouter
我在包含所有文件的src文件夹中运行了go get
命令来获取gorilla,但这并没有解决问题。我在这里做错了什么?
英文:
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?
答案1
得分: 3
如果你的main
包包含多个.go
文件,你需要将它们全部传递给go run
命令,例如:
go run Main.go Router.go
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论