在Go语言中使用全局变量。

huangapple go评论83阅读模式
英文:

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

huangapple
  • 本文由 发表于 2015年2月19日 02:49:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/28591530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定