gpt4 book ai didi

go - 运行多文件go程序

转载 作者:数据小太阳 更新时间:2023-10-29 03:33:27 25 4
gpt4 key购买 nike

所以我是新手,我正在努力学习本教程 -

http://thenewstack.io/make-a-restful-json-api-go/

现在,这是我的文件结构 -

EdData/
dataEntry/
populateDb.go
main.go
handlers.go
routes.go

当我运行 go run main.go ,我收到此错误 ./main.go:11: undefined: NewRouter

这是我的 main.go 的样子 -

package main 

import (
"net/http"
"log"
)



func main() {
router := NewRouter()

log.Fatal(http.ListenAndServe(":8080", router))

}

func checkErr(err error) {
if err != nil {
panic(err)
}
}

这是我的 routes.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,
},
}

这就是我的 handlers.go 的样子

package main

import (
"fmt"
"net/http"
)

func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "WELCOME!")
}

当我尝试构建 routes.go 时,我得到 Index is undefined,当我尝试构建 handlers.go 时,我得到

# command-line-arguments
runtime.main: undefined: main.main

我如何让它运行?另外,我在哪里执行 go run 命令?我需要手动构建所有依赖文件吗?

最佳答案

来自 go run 帮助:

usage: run [build flags] [-exec xprog] gofiles... [arguments...]

Run compiles and runs the main package comprising the named Go source files.
A Go source file is defined to be a file ending in a literal ".go" suffix.

只有传递给 go run 的文件才会包含在编译中(不包括导入的包)。因此,您应该在使用 go run 时指定所有 Go 源文件:

go run *.go
# or
go run main.go handlers.go routes.go

关于go - 运行多文件go程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30766840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com