Rest 在golang中使用全局变量

Rest 在golang中使用全局变量,rest,go,Rest,Go,我有一个全局变量,我正试图在两个不同的函数中使用它,但我无法理解为什么下面的代码不起作用 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

我有一个全局变量,我正试图在两个不同的函数中使用它,但我无法理解为什么下面的代码不起作用

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()的结尾,则它可以正常工作


我做错了什么?

你的问题有两方面

首先,你声明

var api rest.Api
但是rest.New()返回一个*rest.Api

func NewApi() *Api {
其次,在
foo()
函数中,您正在创建一个名为
api
的局部变量,而不是使用包变量

而不是

api := rest.NewApi()
应该是

api = rest.NewApi()

因此,修复方法是在
var-Api*rest.Api
中的
*
之前添加一个
*
,并从Api设置中删除一个冒号,如
Api=rest.NewApi()

是的,您是对的。在我的回答中,我错过了api分配的
:=
。正如您所指出的,全局var肯定需要成为一个指针。
api = rest.NewApi()