dtx9931 2015-06-10 20:38
浏览 11
已采纳

运行多文件go程序

So I'm pretty new to go and I'm trying to follow this tutorial -

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

Right now, this is my file structure -

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

When I run go run main.go, I get this error ./main.go:11: undefined: NewRouter

This is what my main.go looks like -

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)
    }
}

This is what my routes.go looks like

    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,
    },
}

and this is what my handlers.go looks like

package main

import (
    "fmt"
    "net/http"
)

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

When I try and build routes.go, I get that Index is undefined, and when I try and build handlers.go, I get

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

How do I get this to run? Also, where do I execute the go run command? Do I need to manually build all the dependent files?

  • 写回答

1条回答 默认 最新

  • dravpuso44681 2015-06-10 20:42
    关注

    From the go run help:

    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.
    

    Only the files passed to go run will be included in the compilation (excluding imported packages). Therefore, you should specify all of your Go source files when using go run:

    go run *.go
    # or
    go run main.go handlers.go routes.go
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题