【问题标题】:Go cannot call NewRouter() function [duplicate]Go 无法调用 NewRouter() 函数
【发布时间】:2016-01-20 16:27:26
【问题描述】:

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

【问题讨论】:

    标签: go gorilla mux


    【解决方案1】:

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

    go run Main.go Router.go
    

    【讨论】:

    • 天哪,太尴尬了!原来是这样……非常感谢您的回答!
    猜你喜欢
    • 2020-02-01
    • 1970-01-01
    • 2011-09-01
    • 2019-08-27
    • 2019-03-30
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    相关资源
    最近更新 更多