Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a global variable in golang

Tags:

rest

go

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?

like image 500
steve landiss Avatar asked Dec 15 '22 16:12

steve landiss


1 Answers

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

like image 138
sberry Avatar answered Dec 17 '22 04:12

sberry