主包文件中的route方法变得未定义 [英] route method becomes undefined in main package file

查看:141
本文介绍了主包文件中的route方法变得未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下所示:

app.go

package main

import (
    "github.com/go-martini/martini"
)

func main() {
    app := martini.Classic()

    app.Group("/books", func(r martini.Router) {

        r.Get("/:id", getBooks)
        r.Post("/new", newBook)
        r.Put("/update/:id", updateBook)
        r.Delete("/delete/:id", deleteBook)
    })

    app.RunOnAddr(":8080")
}

main.go

package main

import "github.com/go-martini/martini"

func getBooks() string {

    return "get books api called"
}

func newBook() string {
    return "Psot book api called"
}

func updateBook(params martini.Params) string {
    return "put api called " + params["id"]
}

func deleteBook(params martini.Params) string {
    return "delete api called " + params["id"]
}

但是以某种方式,当我运行代码时,它给了我以下错误:

But somehow when I run the code , it gives me the following error :

./app.go:16:17: undefined: getBooks ./app.go:17:18: undefined: newBook ./app.go:18:24: undefined: updateBook ./app.go:19:27: undefined: deleteBook

./app.go:16:17: undefined: getBooks ./app.go:17:18: undefined: newBook ./app.go:18:24: undefined: updateBook ./app.go:19:27: undefined: deleteBook

那么有什么办法可以解决这个问题?

So is there any way to solve this problem?

项目结构如下:

goProject
---->app.go
---->main.go

推荐答案

有两个问题:

您需要将两个文件放在相同的目录中,并且使用相同的包名;即main.

You need to have both files in the same directory with the same package name; namely, main.

您需要编译并执行此目录中的所有文件,您可以使用以下两种方法之一进行操作:

You need to compile and execute all files in this directory which you can do either using:

  • go run ./...执行该目录中的所有文件,或者

  • go run ./... to execute all files in this directory, or,

go run app.go main.go仅执行这两个文件.

或者,按照@mkopriva的建议,您可以将所有处理程序函数移动并导出到其他程序包中,我们将其称为package handlers,然后将其导入到您的main应用程序中.

Alternatively, as suggested by @mkopriva, you can move and export all handler functions to a different package, let's call it package handlers and just import this package in your main app.

这篇关于主包文件中的route方法变得未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆