英文:
Using a global variable in golang
问题
我有一个全局变量,我试图在两个不同的函数之间使用它,但无法弄清楚为什么以下代码不起作用...
package main
import (
"github.com/ant0ine/go-json-rest/rest"
"log"
"net"
"net/http"
)
type Message struct {
Body string
}
var api rest.Api
func hostLookup(w rest.ResponseWriter, req *rest.Request) {
ip, err := net.LookupIP(req.PathParam("host"))
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&ip)
}
func foo() {
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
router, err := rest.MakeRouter(
&rest.Route{"GET", "/lookup/#host", hostLookup},
)
if err != nil {
log.Fatal(err)
}
api.SetApp(router)
}
func bar() {
log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
func main() {
foo()
bar()
}
上述代码不起作用... HTTP服务器无法将请求路由到hostLookup函数。
然而,如果我将以下行从bar()函数中移动到foo()函数的末尾,那么它就能正常工作:
log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
我做错了什么?
英文:
I have a global variable that I am trying to use across two different functions, and unable to figure out why the following code is not working...
package main
import (
"github.com/ant0ine/go-json-rest/rest"
"log"
"net"
"net/http"
)
type Message struct {
Body string
}
var api rest.Api
func hostLookup(w rest.ResponseWriter, req *rest.Request) {
ip, err := net.LookupIP(req.PathParam("host"))
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteJson(&ip)
}
func foo() {
api := rest.NewApi()
api.Use(rest.DefaultDevStack...)
router, err := rest.MakeRouter(
&rest.Route{"GET", "/lookup/#host", hostLookup},
)
if err != nil {
log.Fatal(err)
}
api.SetApp(router)
}
func bar() {
log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}
func main() {
foo()
bar()
}
The above code does not work... the HTTP server does not route the request to the hostLookup function.
However - if I move the following line from bar()
log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
to the end of function foo(), then it works correctly
What am I doing wrong?
答案1
得分: 13
你的问题有两个方面...
首先,你声明了
var api rest.Api
但是 rest.New() 返回的是 *rest.Api
func NewApi() *Api {
其次,在你的 foo()
函数中,你创建了一个名为 api
的局部变量,而不是使用你的包变量。
所以,不应该是
api := rest.NewApi()
而应该是
api = rest.NewApi()
所以,修复的方法是在 rest.Api
前面加上 *
,即 var api *rest.Api
,并且在设置 api 的时候去掉冒号,即 api = rest.NewApi()
。
英文:
Your problem is two fold...
For one, you declare
var api rest.Api
but the rest.New() returns a *rest.Api
func NewApi() *Api {
Secondly, in your foo()
function, you are creating a local variable called api
instead of using your package variable.
Instead of
api := rest.NewApi()
It should be
api = rest.NewApi()
So, the fix is to add a *
before rest.Api
as in var api *rest.Api
and remove a colon from the setting of api as in api = rest.NewApi()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论