douping6871 2016-01-20 16:27
浏览 343
已采纳

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 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器