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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With