I have just started development of a REST api with GoLang. I have a class with some methods in the backend. The rest api should call one of the methods of the class and return the json response. I am having problem calling the object method or passing the object by reference. My cods looks like this.
package main
import (
"time"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"./objects")
/*Global Variables*/
var host objects.HostOS // I have declared this to see if I can have a global variable and later on assign the actual object to that and call that object in the GetStats router method below.
func main() {
fmt.Println("Hello World")
hostConfig := objects.HostConfig{CPUConfig: cpuConfig, MemoryKB: 4096, OSMemoryKB: 1024, OSCompute: 100}
host := new(objects.HostOS)
host.Init(hostConfig)
host.Boot()
time.Sleep(3 * time.Second)
process := new(objects.Process)
process.Init(objects.ProcessConfig{MinThreadCount: 2, MaxThreadCount: 8, ParentOSInstance: host})
process.Start()
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", Index)
router.HandleFunc("/get_os_stats", GetOSStats)
log.Fatal(http.ListenAndServe(":8080", router))
//host.GetStatsJson()
}
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome!")
}
func GetOSStats(w http.ResponseWriter, r *http.Request) {
// js, err := host.GetStatsJson() // This is what I would like to do
// Ideally I would get the Marshalled json and err and return them.
// The object method works fine as I have tested it, I am however unable to call the object method here.
fmt.Println("getting json stats")
host.GetStatsJson() //This is were I get the server panic issue and the code breaks
//I would like to access the method of the 'host' object defined in the main() method.
fmt.Fprintln(w, "GetOSStats!")
}
I would like to call the method of the object defined in the main() function inside the GetOSStats() method and then return the json output.
When I declare a global variable and then later on assign it in the main function, the GetOSStats() function is still accessing a nil struct.
When I declare the host obj in the main function and try to access it in the GetOSStats() funtion, it throws exception.
I think I have to pass the host obj by reference to the GetOSStats() function while calling it in the main but I am not sure about how to do that. I have tried looking up the documentations and the examples but I couldnot find anything that could help me.
Thanks in advance,