Go 无法调用 NewRouter() 函数

标签 go gorilla mux

<分区>

我是 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,但并没有解决问题。我在这里做错了什么?

最佳答案

如果你的 main 包包含多个 .go 文件,你必须将所有文件传递给 go run,例如:

go run Main.go Router.go

关于Go 无法调用 NewRouter() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34905339/

相关文章:

go - Gorilla Websocket客户端读取消息错误

node.js - 在 golang 中为 http 响应创建自定义错误

go - 测试中的模拟方法

go - 使用指针时,omitempty 在编码/xml 中不起作用?

mysql - 处理超过 20 条记录时出现问题

go - 当请求到达根目录时,从另一个目录提供文件

go - gorilla Mux相同端点多个查询参数

mongodb - 在 http 中输出一个 .mp4 文件,从数据库中提取到浏览器

go - 在 LoggingHandlers 中自定义日志格式 在 GO 中的 Gorilla 处理程序中实现

session - 如何使用 String 扩展 session.Value