douping6871
2016-01-20 16:27 阅读 117
已采纳

Go无法调用NewRouter()函数[重复]

This question already has an answer here:

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?

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    douyi8760 douyi8760 2016-01-20 16:38

    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
    
    点赞 评论 复制链接分享

相关推荐