转:同一包中的未定义函数 [英] Go: undefined function in same package
本文介绍了转:同一包中的未定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I've started Go and am trying to follow this tutorial. Everything builds correct but as I try to run it, I get the error that makeRouter()
could not be found.
我看了一些其他问题,例如 ,然后检查了一下文档,但我找不到我的设置有什么问题.
I had a look at some other questions, like this one, and checked the docs, but I couldn't find out whats wrong with my setup.
.../wattagebazooka/
|- wattagebazooka.go
|- router.go
|- handler.go
代码
wattagebazooka.go
Code
wattagebazooka.gopackage main
import (
"database/sql"
"fmt"
"log"
"net/http"
"runtime"
_ "github.com/lib/pq"
)
// init sets runtime settings.
func init() {
// Verbose logging with file name and line number
log.SetFlags(log.Lshortfile)
// Use all CPU cores
runtime.GOMAXPROCS(runtime.NumCPU())
}
var db *sql.DB
func main() {
db = openDB()
defer db.Close()
r := makeRouter()
http.Handle("/", r)
}
func openDB() *sql.DB {
dbName := "wattagebazooka"
db, err := sql.Open("postgres", fmt.Sprintf("user=ts password= dbname=%s host=127.0.0.1", dbName))
if err != nil {
log.Fatalf("Error connecting to the %s database as user ts: %v", dbName, err)
}
return db
}
router.go
package main
import "github.com/gorilla/mux"
func makeRouter() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/user/me", wrapHandler(userHandler)).Methods("GET")
r.HandleFunc("/text", wrapHandler(textHandler)).Methods("POST")
r.HandleFunc("/text/{hash}", wrapHandler(textHashHandler)).Methods("GET")
return r
}
构建
> Environment:
> GOROOT=/usr/local/go
> GOPATH=/Users/ts/Developments/gocode
> Directory: /Users/ts/Developments/gocode/src/github.com/wattagebazooka/wattagebazooka
> Command: /usr/local/go/bin/go build -v
> Output:
github.com/wattagebazooka/wattagebazooka
> Elapsed: 0.708s
> Result: Success
运行
> Environment:
> GOROOT=/usr/local/go
> GOPATH=/Users/ts/Developments/gocode
> Directory: /Users/ts/Developments/gocode/src/github.com/wattagebazooka/wattagebazooka
> Command: /usr/local/go/bin/go run -v /Users/ts/Developments/gocode/src/github.com/wattagebazooka/wattagebazooka/wattagebazooka.go
> Output:
command-line-arguments
# command-line-arguments
./wattagebazooka.go:28:7: undefined: makeRouter
> Elapsed: 0.244s
> Result: Error
推荐答案
通过 go run
运行程序时,需要将所有源文件添加到命令中.
When you run your program via go run
you need to add all source files to the command.
在您的情况下,您只有 wattagebazooka.go
,但缺少 router.go
和 handler.go
.
In your case, you only have wattagebazooka.go
but are missing router.go
and handler.go
.
这篇关于转:同一包中的未定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文