运行多文件转到程序

时间:2015-06-10 20:38:00

标签: go

所以我很新,我正在尝试按照本教程 -

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时,我得到的索引是未定义的,当我尝试构建handlers.go时,我得到了

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

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

1 个答案:

答案 0 :(得分:2)

来自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